Looping in JSX files
I am trying to render a dynamic list of elements using React, ie I have a javascript array elems = ['foo','bar']
and I would like to generate
<ul>
<li>foo</li>
<li>bar</li>
</ul>
I would like to do this purely in JSX. Is there any convenient way to do this (an "equivalent" of angular ng-repeat
)?
The beauty of React/JSX is that you basically just write JavaScript. So if you have a list of things and want to create a list of components, just map
the list:
<ul>
{items.map(item => <li>{item}</li>)}
</ul>
(and it's also really concise with arrow functions)
There is no pure JSX way to do this (that I know of). There is no equivalent to ng-repeat
in React. But, JSX isn't really pure in the same way that Angular templates are. They compile down to JavaScript, after all.
The best way is to loop the JSX and add it to an array:
render: function() {
var elems = ['foo','bar'];
var listItems = [];
for (var i = 0; i < elems.length; i++) {
listItems.push(<li>{elems[i]}</li>);
}
return (
<ul>
{listItems}
</ul>
);
}
You still can use JSX inside the loop as you push
into the array:
listItems.push(<li>{elems[i]}</li>);
链接地址: http://www.djcxy.com/p/52060.html
上一篇: 我如何迭代Reactjs中的一个json对象数组?
下一篇: 在JSX文件中循环播放