我试图在React JSX(其中ObjectRow是一个单独的组件)中执行以下操作:

<tbody>
    for (var i=0; i < numrows; i++) {
        <ObjectRow/>
    } 
</tbody>

我意识到并理解为什么这不是有效的JSX,因为JSX映射到函数调用。然而,由于来自模板领域,而且是JSX的新手,我不确定如何实现上述目标(多次添加组件)。


当前回答

可以在reactjs中对循环使用.map()

    <tbody>
        {items.map((value, index) => {
          return <li key={index}>{value}</li>
        })}
      </tbody>
)

其他回答

我使用这个:

gridItems = this.state.applications.map(app =>
          <ApplicationItem key={app.Id} app={app } />
);

PS:千万不要忘记钥匙,否则会有很多警告!

如果你真的想要一个for循环等价物(你有一个数字,而不是一个数组),只需使用Lodash中的范围。

不要重新发明轮子,不要混淆代码。只需使用标准实用程序库。

import range from 'lodash/range'

range(4);
// => [0, 1, 2, 3]

range(1, 5);
// => [1, 2, 3, 4]
const numrows = [1, 2, 3, 4, 5];

cosnt renderRows = () => {
    return numros.map((itm,index) => <td key={index}>{itm}</td>)
}

return <table>
    ............
    <tr>
        {renderRows()}
    </tr>
</table>

JSX内部的循环非常简单。试试看:

return this.state.data.map((item, index) => (
  <ComponentName key={index} data={item} />
));

…或者,您也可以准备一个对象数组,并将其映射到函数以获得所需的输出。我更喜欢这一点,因为它有助于我保持在渲染返回中没有逻辑的良好编码实践。

render() {
const mapItem = [];
for(let i =0;i<item.length;i++) 
  mapItem.push(i);
const singleItem => (item, index) {
 // item the single item in the array 
 // the index of the item in the array
 // can implement any logic here
 return (
  <ObjectRow/>
)

}
  return(
   <tbody>{mapItem.map(singleItem)}</tbody>
  )
}