[英]Conditionally render <td> in a React component
這是我在頁面上顯示的JSX要點。
rows.push(
<tr key={i}>
<td>{this.state['Person Name'] && this.state['Person Name'][i]}</td>
<td>{this.state['Amount'] && this.state['Amount'][i]}</td>
{this.state['Memo'] && this.state['Memo'].length > 0 ? <td>{this.state['Memo'][i]}</td> : undefined}
{this.state['Comment'] && this.state['Comment'].length > 0 ? <td>{this.state['Comment'][i]}</td> : undefined}
{this.state['Incurred Date'] && this.state['Incurred Date'].length > 0 ? <td>{this.state['Incurred Date'][i]}</td> : undefined}
{this.state['Entry Date'] && this.state['Entry Date'].length > 0 ? <td>{this.state['Entry Date'][i]}</td> : undefined}
<td>{this.state['Billable'] && this.state['Billable'][i]}</td>
<td>{this.state.fileName === 'expenses.csv' ? 'Expense' : 'Time'}</td>
</tr>
)
不知何故的條件仍然在表中顯示空的<td>
。 我錯過了什么?
空列如上所示。
您根本不需要使用三元運算符。 只需連鎖&&
。
{this.state.Memo && this.state.Memo[i] && <td>{this.state.Memo[i]}</td>}
{this.state.Comment && this.state.Comment[i] && <td>{this.state.Comment[i]}</td>}
{this.state['Incurred Date'] && this.state['Incurred Date'][i] && <td>{this.state['Incurred Date'][i]}</td>}
{this.state['Entry Date'] && this.state['Entry Date'][i] && <td>{this.state['Entry Date'][i]}</td>}
另外,您的數組似乎格式錯誤:
// 2 separate variables for the same data?
this.memo = ['a', 'b'];
this.comment = ['comment', 'comment2'];
// Why not make it an array like this?
this.rows = [
{
Memo: 'a',
Comment: 'comment'
},
{
Memo: 'b',
Comment: 'comment2'
}
];
然后,您可以簡單地執行以下操作:
this.rows.map(row => (
<tr key={row.id}>
<td>{row['Person Name']}</td>
<td>{row['Amount']}</td>
{this.state.hasMemos && <td>{row.Memo}</td>}
...
</tr>
)}
<td>
不應以行級別為條件,而應以表級別為條件。 如果該行沒有數據,就不能簡單地跳過TD,因為它會通過將列移至來拋出整行 。 您應該顯示N / A,對於可能沒有數據的行顯示一個空的<td></td>
,或者如果有任何備注,則可以通過this.state.hasMemos
東西將它們完全隱藏在表級別。
如果您使用的是我列出的新數組結構,則可以使用此函數來確定是否有任何行具有備注:
this.array.some(row => row.Memo);
如果任何行都有備注,則將返回true,從而為整個表隱藏<td>
或為每行顯示它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.