1. 程式人生 > >Inline Styles for Basic Pseudo-Classes

Inline Styles for Basic Pseudo-Classes

My first blocker with inline-styles was pseudo-classes. I make lots of lists. So, I felt pretty exposed without :first-child() and friends.

Let’s try recreating some of these handy selectors using map().

What’s a map()?

If you’re new to React, chances are you’ve already seen sample uses of map(). But maybe you’re not entirely sure what it does. Let’s step through it.

map() is a function called on an array

[1, 2, 3].map()

map() takes a function as an argument

[1, 2, 3].map(function () {});

This function is called with each element in the array

[1, 2, 3].map(function (n) { return n });
// => function (1) { return 1 }
// => function (2) { return 2 }
// => function (3) { return 3 }

A new array is then created — and returned — with all the new values

[1, 2, 3].map(function (n) { return n + 1 });
// => [2, 3, 4]

Map also provides the index of each element

[1, 2, 3].map(function (n, i) { /* ... */ });
// => function (1, 0)
// => function (2, 1)
// => function (3, 2)

We’ll use this index to emulate pseudo-classes.

The Setup

Assume we have a render function like this:

<ul>
{this.props.items.map((item, i) => {
return <Item highlight={i === 0} item={item} />;
})}
</ul>

Pretty common. For each item, we create a new <Item> component. <Item> takes highlight as a prop and applies styles accordingly.

I want to focus on the expression needed to get <Item> highlighting the right elements:

{i === 0}