如何使用Array.map函数将交替颜色传递给组件?

3

我正在尝试向React应用程序中的子组件发送交替颜色作为属性,并且我不太确定该如何实现。每个StatLine组件的颜色应该交替出现。我希望使用map,因为我的数组是动态的,在渲染时写出数组的每一行似乎是不必要的。

render() {

const { stats } = this.state;

//var alternatingColor = #d5d5d5;
//var alternatingColor = #a9a9a9;

const Stats = stats.map((season) => {
    return <StatLine color={alternatingColor}  {...season}/>;
});

return (
  <div>
   {Stats}
  </div>
);

有没有一种使用Array.map函数简单的方法来完成这个操作

5个回答

7
创建一个交替颜色的数组:
const alternatingColor = ['#d5d5d5', '#a9a9a9']; // because this is a static array, you can move it out of the component

使用Array#map的第二个参数获取项目的索引:
stats.map((season, index) => {

使用余数运算符%从数组中获取颜色:
<StatLine color={alternatingColor[index % alternatingColor.length]} {...season}/>

渲染方法(未经测试):

render() {

  const alternatingColor = ['#d5d5d5', '#a9a9a9']; // you can move it out of the render method

  const Stats = stats.map((season, index) => {
      return <StatLine color={alternatingColor[index % alternatingColor.length]}  {...season}/>;
  });

  return (
    <div>
     {Stats}
    </div>
  );
};

1
@Kimmiekim - 很高兴能帮到你 :) - Ori Drori

3

Array.map 还提供了当前元素的索引,您可以使用该索引在十六进制值之间进行交替:

const Stats = stats.map((season, i) => <StatLine color={ i % 2 ? '#d5d5d5' : '#a9a9a9' } { ...season } />)

3
render() {

const { stats } = this.state;

//var alternatingColor = #d5d5d5;
//var alternatingColor = #a9a9a9;

const Stats = stats.map((season, index) => {
    return index %2 == 0 ?  <StatLine color={this.props.color}  {...season}/>
   : <StatLine color={this.props.alternatingColor}  {...season}/>
;
});

return (
  <div>
   {Stats}
  </div>
);
}

1
如果我理解正确,您可以这样做:
const colors = ['#d5d5d5', '#a9a9a9'] 

const Stats = stats.map((season, index) => {
    return <StatLine color={index % 2 ? colors[0] : colors[1]}  {...season}/>;
});

Array.prototype.map回调函数中,第二个参数是当前迭代项的索引,因此您可以使用它来计算模数并以交替方式应用颜色。

0
var alternatingColor;

const Stats = stats.map((season) => {
    alternatingColor = alternatingColor == '#d5d5d5' ? '#a9a9a9' : '#d5d5d5';
    return <StatLine color={alternatingColor}  {...season}/>;
});

alternatingColor 总是未定义的,因此颜色将始终为 '#d5d5d5'。 - csander
@csander 不会的,在第一次迭代中只有未定义。请注意alternatingColormap之外定义,因此它将保留对该值所做的任何更改。 - FuzzyTree
1
是的,但你的回答中没有任何赋值操作。 - csander

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接