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

How to conditionally add closing and starting JSX tags

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

<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>

你应该关闭花括号内的HTML标签{},除非它是在花括号内创建的。

示例:

<div>
{</div>} //wrong

<div>
  {1 + 5}
</div> //correct

<div>
  {2+3 === 5 ? <div>hello</div> : <div>world</div>}
</div> //correct

<div>
  {2+3 === 5 ? <div>{6 + 7}</div> : <div>{5 + 5}</div>}
</div> //correct

除此之外,{} 只能包含 HTML 标签的单个节点。如果 {} 里面有多个 HTML 的节点,React 会抛出错误。

例子

<div>
 {
  <span>{1+2}</span>
  <span>{1+2}</span>
 }
</div> //will throw an error

<div>
 {
  <span>
   <span>{1+2}</span>
   <span>{1+2}</span>
  </span> 
 } 
</div> //correct

希望对您有所帮助!!

[更新]

针对您的情况

{
 true //if true, this table will be rendered, else, null will be returned
  ? <table>
  <thead>
    ...
  </thead>
 </table>
 : null
}
<table> //this table will render all the time
 <tbody>
     ...
 </tbody>
</table>

我找不到解决这个问题的方法,所以我只是用 if 语句手动解决了这个问题。

if (condition === true) {
    return (<table>...</table> <table>...</table>);
} else {
    return (<table>...</table>);
}

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

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>
}