如何访问状态数组中的元素,例如
this.state = {
items: [1,5,22,6],
}
这里我正在尝试设置一个类,如果id存在于状态
中{this.props.data.map((row)=> (
<ul>
<li key={row.id} className={row.id === this.state.items ? 'complete' : 'pending'}" >{row.name}</li>
</ul>
))}
答案 0 :(得分:3)
您可以对数组使用.includes()函数:
{this.props.data.map((row)=> (
<ul>
<li key={row.id} className={this.state.items.includes(row.id) ? 'complete' : 'pending' }>{row.name}</li>
</ul>
))}
或者使用.indexOf():
{this.props.data.map((row)=> (
<ul>
<li key={row.id} className={this.state.items.indexOf(row.id) !== -1 ? 'complete' : 'pending' }>{row.name}</li>
</ul>
))}