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

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

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


当前回答

当我想添加一定数量的组件时,我使用助手函数。

定义一个返回JSX的函数:

const myExample = () => {
    let myArray = []
    for(let i = 0; i<5;i++) {
        myArray.push(<MyComponent/>)
    }
    return myArray
}

//... in JSX

<tbody>
    {myExample()}
</tbody>

其他回答

我用它就像

<tbody>
  { numrows ? (
     numrows.map(obj => { return <ObjectRow /> }) 
    ) : null
  }
</tbody>
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>

有几个答案指向使用map语句。下面是一个完整的示例,它使用FeatureList组件中的迭代器基于一个称为features的JSON数据结构列出Feature组件。

const FeatureList = ({ features, onClickFeature, onClickLikes }) => (
  <div className="feature-list">
    {features.map(feature =>
      <Feature
        key={feature.id}
        {...feature}
        onClickFeature={() => onClickFeature(feature.id)}
        onClickLikes={() => onClickLikes(feature.id)}
      />
    )}
  </div>
); 

您可以在GitHub上查看完整的FeatureList代码。此处列出了特征夹具。

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

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

您可以尝试新的for of循环:

const apple = {
    color: 'red',
    size: 'medium',
    weight: 12,
    sugar: 10
}
for (const prop of apple.entries()){
    console.log(prop);
}

以下是几个示例: