How to conditionally add closing and starting JSX tags

淺唱寂寞╮ 提交于 2019-12-07 07:01:27

问题


I have never been able to figure out how to conditionally close off an existing JSX tag and start a new one without getting syntax errors in Visual Studio. How is this done? In the example below, I want to split an existing table into two tables. I don't get any syntax errors if I remove the conditional code.

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

回答1:


I solved this by creating a renderTable(rows) method that I call for each group of rows that need to be in a separate 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>
}



回答2:


I could not find a workaround for this problem, so I just manually solved the problem with an if statement.

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



回答3:


You should not close a HTML tag inside the curly braces {}, unless it is created inside the curly braces.

Examples:

<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

Adding to that, {} can contain only a single node of HTML tag. If you have multiple nodes of HTML inside {}, React will throw an error.

Examples

<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

Hope it help!!

[Update]

For your case

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


来源:https://stackoverflow.com/questions/39774851/how-to-conditionally-add-closing-and-starting-jsx-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!