react jsx 循环
If you have a set of elements you need to loop upon to generate a JSX partial, you can create a loop, and then add JSX to an array:
如果有一组元素需要循环以生成JSX部分,则可以创建一个循环,然后将JSX添加到数组中:
const elements = [] //..some array
const items = []
for ( const [ index , value ] of elements . entries ()) {
items . push ( < Element key = { index } /> )
}
Now when rendering the JSX you can embed the items
array by wrapping it in curly braces:
现在,当渲染JSX时,您可以通过将其包装在花括号中来嵌入items
数组:
render () {
const elements = [ 'one' , 'two' , 'three' ];
const items = []
for ( const [ index , value ] of elements . entries ()) {
items . push ( < li key = { index } > { value } < /li>)
}
return (
< div >
{ items }
< /div>
)
}
You can do the same directly in the JSX, using map
instead of a for-of loop:
您可以使用map
而不是for-of循环直接在JSX中执行相同的操作:
render : function () {
const elements = [ 'one' , 'two' , 'three' ];
return (
< ul >
{ elements . map (( value , index ) => {
return < li key = { index } > { value } < /li>
})}
< /ul>
)
}
react jsx 循环