简体   繁体   English

从 javascript 函数返回多个反应组件

[英]Return multiple react components from a javascript function

I'm trying to build a table dynamically in React.我正在尝试在 React 中动态构建一个表。 The cells in the table will come from the dataset property on an incoming HTML object.表格中的单元格将来自传入 HTML 对象的dataset属性。 The table will have two columns - the name of the attribute and the value of the attribute.该表将有两列 - 属性名称和属性值。

This function builds the outer table:此函数构建外部表:

  buildDataList = () => (
    <Scroll>
      <Table isStriped key={this.claimCountLimitPerFin} >
        <Table.Header>
          <Table.HeaderCell content="Name" minWidth="medium" />
          <Table.HeaderCell content="Value" minWidth="medium" />
        </Table.Header>
        <Table.MultiSelectableRows // this is probably not necessary?
          maxSelectionCount={10}
        >
          {this.buildTableRows2()}

        </Table.MultiSelectableRows>
      </Table>
    </Scroll>
  );

This is the function that I'm calling to build the TableRows :这是我调用以构建TableRows的函数:

  buildTableRows2 = () => {
    Object.keys(this.props.dataset).forEach(datum => <Table.Row
      id={datum}
      key={`ROW_${datum}`}
    >
      {this.buildTextCell(datum)}
      {this.buildTextCell(this.props.dataset[datum])}
    </Table.Row>);
  }

I cannot figure out how to get buildTableRows2 to return all of the TableRow s!我不知道如何让buildTableRows2返回所有的TableRow It isn't returning any, though I see that it is looping through all the attributes of dataset as I expect.它没有返回任何内容,但我看到它正在按照我的预期循环遍历数据集的所有属性。 I tried wrapping it in a React fragment, but that didn't work.我尝试将它包装在 React 片段中,但这没有用。 I can't think of any other possible solutions.我想不出任何其他可能的解决方案。 Any ideas?有任何想法吗?

Two problems in your code:您的代码中有两个问题:

  • You are not returning anything from the buildTableRows2() function.您没有从buildTableRows2()函数返回任何内容。 You need to add a return keyword before Object.keys() inside buildTableRows2() function.您需要在buildTableRows2()函数内的Object.keys()之前添加return关键字。
  • .forEach() method doesn't returns anything, you will need to use .map() method. .forEach()方法不返回任何内容,您需要使用.map()方法。

Change the buildTableRows2() function as shown below:更改buildTableRows2()函数,如下所示:

buildTableRows2 = () => {
    return Object.keys(this.props.dataset).map(datum => (
       <Table.Row
         id={datum}
         key={`ROW_${datum}`}
       >
         {this.buildTextCell(datum)}
         {this.buildTextCell(this.props.dataset[datum])}
       </Table.Row>
    );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM