admin管理员组文章数量:1326059
I'm a newbie in React and I have an app that should render different <p>
with different colors from an array.
as for my latest code
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>
)
}
})
I'm a newbie in React and I have an app that should render different <p>
with different colors from an array.
as for my latest code
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>
)
}
})
and the output should be like this:
Thanks in advance.
Share Improve this question asked Jan 6, 2017 at 10:06 kcNekokcNeko 6091 gold badge9 silver badges23 bronze badges1 Answer
Reset to default 6You can use the iterator of the map to set the style
of the p
element accordingly.
In 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./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='View'></div>
In ES5 (with createClass
, which is not remended):
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./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='View'></div>
本文标签: javascriptReactarray of colors will change color ltpgtStack Overflow
版权声明:本文标题:javascript - React - array of colors will change color <p> - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742197836a2431408.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论