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

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

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


当前回答

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

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>
  )
}

其他回答

您可能需要签出React Templates,它允许您在React中使用JSX样式的模板,并带有一些指令(例如rt repeat)。

如果使用反应模板,您的示例如下:

<tbody>
     <ObjectRow rt-repeat="obj in objects"/>
</tbody>

JSX内部有多种循环方式

使用for循环函数TableBodyForLoop(props){常量行=[];//创建数组以存储tr列表for(设i=0;i<props.people.length;i++){const person=道具.人物[i];//将tr推到数组,关键是行.推(<tr key={person.id}><td>{person.id}</td><td>{人名}</td></tr>);}//返回tbody内的行return<tbody>{rows}</tbody>;}使用ES6阵列映射方法函数TableBody(props){返回(<tbody>{props.people.map(person=>(<tr key={person.id}><td>{person.id}</td><td>{人名}</td></tr>))}</tbody>);}

完整示例:https://codesandbox.io/s/cocky-meitner-yztif

以下React文档将有所帮助

列表和键条件渲染

ES2015 Array.from,带有map函数+键

如果对.map()没有任何内容,可以使用Array.from()和map函数来重复元素:

<tbody>
  {Array.from({ length: 5 }, (value, key) => <ObjectRow key={key} />)}
</tbody>

好了,给你。

{
    [1, 2, 3, 4, 5, 6].map((value, index) => {
        return <div key={index}>{value}</div>
    })
}

您所要做的只是映射数组并返回任何要渲染的内容。请不要忘记在返回的元素中使用key。

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>