在 React 中有条件地添加 table n+1 table 行(<tr>)

Conditionally add table n+1 table rows (<tr>) in React

我在将 jsx table 行动态添加到 table 中时遇到问题。

我遇到的情况是这样的:

如果 table 行包含子行,将它们添加到主行之外。

这是我最初的设计:

        {rows.map((row) => {
        const expanded = _.includes(expandedRows, row.name); // check if row is expanded or not
        const subRows = row.subRows && row.subRows.map((subRow) =>
          <SubRow key={subRow.name} theme={theme} subRow={subRow.name} />);

        return (
          <div>
            <Row
              key={row.name}
              theme={theme}
              handleUpdate={handleUpdate}
              handleExpandOrCollapseRow={handleExpandOrCollapseRow}
            />
            {expanded && row.subRows && subRows}
            {expanded && !row.subRows && <p>No subrows exist</p>}
          </div>
        );
      })

问题是 div 不允许作为 tbody 标签中的子项。有什么想法可以解决这个问题而不用将我的 return 包装在 div 中吗?

我正在考虑将整个 tbody 移动到我的 Row 组件并有条件地在那里呈现子行,但我看不出它有什么帮助,因为我仍然无法在 return 周围使用任何包装器...我唯一可以使用的包装器是 tbody,它只能作为所有行的父级出现一次。

有什么想法吗?

而不是 return 将 div 包裹在 tr 的周围,您可以简单地将 rows 收集在 array 中,然后 return array 之后。

这是一个例子

renderTableRows() {
    const rows = [];

    // Push the main row first
    rows.push(
        <Row
            key={row.name}
            theme={theme}
            handleUpdate={handleUpdate}
            handleExpandOrCollapseRow={handleExpandOrCollapseRow}
        />
    );

    // Then push the subrows
    row.subRows.forEach(subRow =>
        rows.push(
            <SubRow key={subRow.name} theme={theme} subRow={subRow.name} />
        );
    );

    return rows;
}

然后像这样将 renderTableRows() 方法添加到您的视图

render() {
    if( this.state.isLoading ) {
        return Table.renderSpinner();
    }

    return (
        <table>
            { this.renderTableRows() }
        </table>
    );
}

我不能确定该代码是否开箱即用。但是这个模式应该可以帮助您解决问题。