React - 颜色数组将改变颜色<p>

时间:2017-01-06 10:06:42

标签: javascript reactjs

我是React的新手,我有一个应用程序应该使用不同颜色的数组呈现不同的<p>

至于我的最新代码

const data1 = [
      {name: 'one'},
      {name: 'two'},
      {name: 'three'},
      {name: 'four'}
];

const colors = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];

export default React.createClass({
  render() {
      return (
          <div>
          {data1.map(function(a) {
              return (
                  <p>{a.name}</p>
                )
            })}
          </div>
        )
  }
})

输出应该是这样的:
enter image description here

提前致谢。

1 个答案:

答案 0 :(得分:5)

您可以使用地图的迭代器相应地设置style元素的p

在ES6中:

const data1 = [
  { name: 'one' },
  { name: 'two' },
  { name: 'three' },
  { name: 'four' }
];

const colors = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];

class Example extends React.Component {
  render() {
    return (
      <div>
        {data1.map((a, i) => <p style={{ color: colors[i] }} key={i}>{a.name}</p>)}
      </div>
    );
  }
}

ReactDOM.render(<Example />, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='View'></div>

在ES5中(createClass,不推荐):

const data1 = [
  { name: 'one' },
  { name: 'two' },
  { name: 'three' },
  { name: 'four' }
];

const colors = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];

const Example = React.createClass({
  render() {
    return (
      <div>
        {data1.map(function(a, i) {
           return (
             <p style={{ color: colors[i] }} key={i}>{a.name}</p>
           );
        })}
      </div>
    );
  }
});

ReactDOM.render(<Example />, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='View'></div>