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

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

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


当前回答

这是我迄今为止在大多数项目中使用的方法:

const length = 5;
...
<tbody>
    {Array.from({ length }).map((_,i) => (
        <ObjectRow key={i}/>
    ))}
</tbody>

其他回答

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

简单的方法

您可以将numrows置于状态,并使用map()代替for循环:

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

您需要向数组中添加元素并渲染元素数组。这有助于减少重新渲染组件所需的时间。

下面是一些可能有用的粗略代码:

MyClass extends Component {
    constructor() {
        super(props)
        this.state = { elements: [] }
    }
    render() {
        return (<tbody>{this.state.elements}<tbody>)
    }
    add() {
        /*
         * The line below is a cheap way of adding to an array in the state.
         * 1) Add <tr> to this.state.elements
         * 2) Trigger a lifecycle update.
         */
        this.setState({
            elements: this.state.elements.concat([<tr key={elements.length}><td>Element</td></tr>])
        })
    }
}

有趣的是,人们如何使用更新的语法或不常见的方法来创建数组,从而给出“创造性”的答案。在我使用JSX的经验中,我见过这些技巧,只有经验不足的React程序员才会使用。

解决方案越简单,对未来的维护人员就越好。由于React是一个web框架,通常这种类型的(表)数据来自API。因此,最简单和最实用的方法是:

const tableRows = [
   {id: 1, title: 'row1'}, 
   {id: 2, title: 'row2'}, 
   {id: 3, title: 'row3'}
]; // Data from the API (domain-driven names would be better of course)
...

return (
   tableRows.map(row => <ObjectRow key={row.id} {...row} />)
);



如果你真的想要一个for循环等价物(你有一个数字,而不是一个数组),只需使用Lodash中的范围。

不要重新发明轮子,不要混淆代码。只需使用标准实用程序库。

import range from 'lodash/range'

range(4);
// => [0, 1, 2, 3]

range(1, 5);
// => [1, 2, 3, 4]