如何有条件地添加结束和开始 JSX 标签

Lam*_*ert 9 reactjs react-jsx

我一直无法弄清楚如何有条件地关闭现有的 JSX 标记并开始一个新的标记,而不会在 Visual Studio 中出现语法错误。这是怎么做的?在下面的示例中,我想将现有表拆分为两个表。如果我删除条件代码,我不会收到任何语法错误。

<table>
    <thead>
        ...
    </thead>

    {true ?
     </table> /* Close first table (Syntax error on this line because of no starting tag) */
     <table>  /* Create a new table by splitting the existing table */
    : null}

    <tbody>
        ...
    </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

Fuz*_*ree 5

我通过创建一个renderTable(rows)方法解决了这个问题,我为需要位于单独表中的每组行调用该方法:

render() {
    let tables = [];
    let tableRows = [];

    this.props.rows.forEach(row => {
        tableRows.push(row);
        if (someCondition()) {
            // end the table after this row
            tables.push(this.renderTable(tableRows));
            tableRows = [];
        }
    });

    if (tableRows.length) {
        tables.push(this.renderTable(tableRows));
    }

    return <div>{tables}</div>;
}

renderTable(rows) {
    return <table>
        <tbody>
        {rows.map ..... }
        </tbody>
    </table>
}
Run Code Online (Sandbox Code Playgroud)