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

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

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


当前回答

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

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

以下是几个示例:

其他回答

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

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

以下是几个示例:

如果没有键值par,则使用以下代码打印数组值-

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

有几个答案指向使用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代码。此处列出了特征夹具。