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

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

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


当前回答

render() {
  const elements = ['one', 'two', 'three'];

  const items = []

  for (const [index, value] of elements.entries()) {
    items.push(<li key={index}>{value}</li>)
  }

  return (
    <div>
      {items}
    </div>
  )
}

其他回答

以下是您可以在React中通过迭代对象数组或普通数组实现的可能解决方案

const rows = [];
const numrows = [{"id" : 01, "name" : "abc"}];
numrows.map((data, i) => {
    rows.push(<ObjectRow key={data.id} name={data.name}/>);
});

<tbody>
    { rows }
</tbody>

Or

const rows = [];
const numrows = [1,2,3,4,5];
for(let i=1, i <= numrows.length; i++){
    rows.push(<ObjectRow key={numrows[i]} />);
};

<tbody>
    { rows }
</tbody>

最近几天,我熟悉的一种更好的迭代对象数组的方法是直接在渲染中使用.map,可以返回也可以不返回:

.map带返回

 const numrows = [{"id" : 01, "name" : "abc"}];
 <tbody>
     {numrows.map(data=> {
         return <ObjectRow key={data.id} name={data.name}/>
     })}
</tbody>

.map不返回

 const numrows = [{"id" : 01, "name" : "abc"}];
 <tbody>
     {numrows.map(data=> (
         <ObjectRow key={data.id} name={data.name}/>
     ))}
</tbody>

你当然可以按照另一个答案的建议用.map来解决。如果您已经使用了Babel,可以考虑使用jsx控制语句。

它们需要一些设置,但我认为在可读性方面是值得的(特别是对于非React开发人员)。如果使用linter,还有eslint-plugin-jsx控制语句。

function PriceList({ self }) {
    let p = 10000;
    let rows = [];
    for(let i=0; i<p; i=i+50) {
        let r = i + 50;
        rows.push(<Dropdown.Item key={i} onClick={() => self.setState({ searchPrice: `${i}-${r}` })}>{i}-{r} &#8378;</Dropdown.Item>);
    }
    return rows;
}

<PriceList self={this} />

一行(假设numrows是一个数字):

<tbody>
  {
    Array(numrows).fill().map(function (v, i) {
      return <ObjectRow/>
    })
  }
</tbody>

为了在您希望使用存储为整型值的特定行计数的情况下提供更直接的解决方案。

在typedArray的帮助下,我们可以通过以下方式实现所需的解决方案。

// Let's create a typedArray with length of `numrows`-value
const typedArray = new Int8Array(numrows); // typedArray.length is now 2
const rows = []; // Prepare rows-array
for (let arrKey in typedArray) { // Iterate keys of typedArray
  rows.push(<ObjectRow key={arrKey} />); // Push to an rows-array
}
// Return rows
return <tbody>{rows}</tbody>;