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

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

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


当前回答

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>

其他回答

想象一下,你只是在调用JavaScript函数。不能在函数调用的参数所在的位置使用for循环:

return tbody(
    for (let i = 0; i < numrows; i++) {
        ObjectRow()
    } 
)

看看函数tbody是如何作为参数传递给for循环的——导致语法错误。

但您可以创建一个数组,然后将其作为参数传入:

const rows = [];
for (let i = 0; i < numrows; i++) {
    rows.push(ObjectRow());
}
return tbody(rows);

使用JSX时,基本上可以使用相同的结构:

const rows = [];
for (let i = 0; i < numrows; i++) {
    // note: we are adding a key prop here to allow react to uniquely identify each
    // element in this array. see: https://reactjs.org/docs/lists-and-keys.html
    rows.push(<ObjectRow key={i} />);
}
return <tbody>{rows}</tbody>;

顺便说一下,我的JavaScript示例几乎与JSX的示例完全相同。玩Babel REPL,了解JSX的工作原理。

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

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

以下是几个示例:

return (
    <table>
       <tbody>
          {
            numrows.map((item, index) => {
              <ObjectRow data={item} key={index}>
            })
          }
       </tbody>
    </table>
);

以下是React文档中的一个示例,JavaScript表达式作为子项:

function Item(props) {
  return <li>{props.message}</li>;
}

function TodoList() {
  const todos = ['finish doc', 'submit pr', 'nag dan to review'];
  return (
    <ul>
      {todos.map((message) => <Item key={message} message={message} />)}
    </ul>
  );
}

至于你的情况,我建议你这样写:

function render() {
  return (
    <tbody>
      {numrows.map((roe, index) => <ObjectRow key={index} />)}
    </tbody>
  );
}

请注意,键非常重要,因为React使用键来区分数组中的数据。

只需执行以下操作:

<tbody>{new Array(numRows).fill(“”,0,numRows”).map((p,i)=><YourRaw key={i}/>)}</tbody>