2016-09-29 58 views
2

我從來沒有能夠找出如何有條件地關閉現有的JSX標籤,並開始一個新的沒有在Visual Studio中的語法錯誤。這是如何完成的?在下面的例子中,我想將現有的表分成兩個表。如果刪除條件代碼,我不會收到任何語法錯誤。如何有條件地添加關閉和啓動JSX標籤

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

你能解釋一下你越要分成兩個數據是什麼表?在進入渲染代碼之前進行分割/過濾可能更直接。 –

+0

@羅斯艾倫 - 我把頭部分成一張桌子,身體分成另一張桌子,這樣我就可以擁有一個固定的頭部。 – Lambert

+0

我建議事先分割數據並防止渲染中需要條件。你可以在代碼示例中包含數據格式的例子嗎? –

回答

0

我通過創建一個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> 
} 
0

你應該關閉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> 
+0

那麼如何有條件地關閉我的示例中的表? – Lambert

+0

@Lambert更新了答案。 –

1

我無法找到此問題的方法,所以我只是手動if語句解決了這個問題。

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