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

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

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


当前回答

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

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

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中创建循环

import React, { Children, Fragment } from 'react';

export const ObjectRow = ({ data }) => (
 <div>
    <Fragment>{data}</Fragment>
 </div>
);


/** Wrapping your list inside React.Children.toArray allows you to not 
pass unique key props.
It will be dynamically generated from Virtual Dom to Real Dom */

export const ObjectRowListComponent = (objectRows) => (
<tbody>
    {Children.toArray(objectRows.map((row) => <ObjectRow data={row} />))}
</tbody>
);

您可以直接在JSX中执行相同的操作,使用map而不是for of循环:

render: function() {
const items = ['one', 'two', 'three'];
 return (
  <ul>
     {items.map((value, index) => {
     return <li key={index}>{value}</li>
     })}
 </ul>
 )
}

只需使用.map()循环遍历集合,并从每个迭代返回带有道具的<ObjectRow>项。

假设对象是某处的数组。。。

<tbody>
  { objects.map((obj, index) => <ObjectRow obj={ obj } key={ index }/> ) }
</tbody>
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} />

您可能需要签出React Templates,它允许您在React中使用JSX样式的模板,并带有一些指令(例如rt repeat)。

如果使用反应模板,您的示例如下:

<tbody>
     <ObjectRow rt-repeat="obj in objects"/>
</tbody>