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

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

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


当前回答

在迭代数组和生成JSX元素方面有很多解决方案。所有这些都很好,但都直接在循环中使用了索引。我们建议使用数据中的唯一id作为键,但如果数组中的每个对象没有唯一id,我们将使用索引作为键,但是不建议直接使用索引作为密钥。

还有一件事,为什么我们选择.map,但为什么不选择foEach,因为.map返回一个新数组。现在有很多不同的方法。

下面使用.map的不同版本详细说明了如何使用唯一键以及如何使用.map循环JSX元素。

当从数据中返回单个JSX元素和唯一id作为密钥版本时,.map不返回:

const {objects} = this.state;

<tbody>
    {objects.map(object => <ObjectRow obj={object} key={object.id} />)}
</tbody>

将数据中的多个JSX元素和唯一id作为密钥版本返回时,不返回.map

const {objects} = this.state;

<tbody>
    {objects.map(object => (
        <div key={object.id}>
            <ObjectRow obj={object} />
        </div>
    ))}
</tbody>

当将单个JSX元素和索引作为键版本返回时,.map没有返回:

const {objects} = this.state;

<tbody>
    {objects.map((object, index) => <ObjectRow obj={object} key={`Key${index}`} />)}
</tbody>

当返回多个JSX元素和索引作为密钥版本时,.map没有返回:

const {objects} = this.state;

<tbody>
    {objects.map((object, index) => (
        <div key={`Key${index}`}>
            <ObjectRow obj={object} />
        </div>
    ))}
</tbody>

.map,当返回多个JSX元素和索引作为键版本时返回:

const {objects} = this.state;

<tbody>
    {objects.map((object, index) => {
        return (
            <div key={`Key${index}`}>
                <ObjectRow obj={object} />
            </div>
        )
    })}
</tbody>

将数据中的多个JSX元素和唯一id作为密钥版本返回时,使用return的.map:

const {objects} = this.state;

<tbody>
    {objects.map(object => {
        return (
            <div key={object.id}>
                <ObjectRow obj={object} />
            </div>
        )
    })}
</tbody>

另一种方式是

render() {
  const {objects} = this.state;
  const objectItems = objects.map(object => {
       return (
           <div key={object.id}>
               <ObjectRow obj={object} />
           </div>
       )
  })
  return(
      <div>
          <tbody>
              {objectItems}
          </tbody>
      </div>
   )
}

其他回答

您可以执行以下操作来重复组件numrows次

<tbody>{Array(numrows).fill(<ObjectRow />)}</tbody>

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

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

这里有一个简单的解决方案。

var Object_rows = [];
for (var i = 0; i < numrows; i++) {
  Object_rows.push(<ObjectRow />);
}
<tbody>{Object_rows}</tbody>;

不需要映射和复杂代码。您只需要将行推送到数组并返回值来渲染它。

问题是您没有返回任何JSX元素。对于这种情况还有另一种解决方案,但我将提供最简单的解决方案:“使用map函数”!

<tbody>
  { numrows.map(item => <ObjectRow key={item.uniqueField} />) }
</tbody>

它是如此简单和美丽,不是吗?

<tbody>
   numrows.map((row,index) => (
      return <ObjectRow key={index}/>
   )
</tbody>