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

IT技术 reactjs react-jsx
2021-04-29 05:02:10

我一直无法弄清楚如何有条件地关闭现有的 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>
3个回答

我通过创建一个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>
}

你应该不会关闭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>);
}