【发布时间】:2019-10-06 03:10:40
【问题描述】:
大家好,目前我在 react 的条件渲染上遇到了问题。
我有 2 个数组保存在 state 中:
this.state = {
arr_one:[1,2,3,4,5],
arr_two:[1,3,5]
};
如果 arr_two 中的项目存在于 arr_one 中,我想用这些数组和条件渲染 div 迭代,然后渲染不同的 div。
注意:我不想用模数条件 (%) 来解决这个问题。
这是我的代码:
代码:
class TestComp extends React.Component {
constructor(props) {
super(props);
this.state = {
arr_one:[1,2,3,4,5],
arr_two:[1,3,5]
};
}
render() {
const filteredStyle={
background:'red'
}
return (
<div className="wrapper">
{
this.state.arr_one.map((item,index)=>
index === this.state.arr_two[index]?
<div key={index} className={filteredStyle}>
<p>Item {item}</p>
</div>
:
<div key={index}>
<p>I'm not in filter! {item}</p>
</div>
)
}
</div>
)
}
}
输出:
我不在过滤器中! 1
我不在过滤器中! 2
我不在过滤器中! 3
我不在过滤器中! 4
我不在过滤器中! 5
预期输出:
项目 1
我不在过滤器中! 2
第 3 项
我不在过滤器中! 4
第 5 项
我也有我的代码演示 CodeSandBox
【问题讨论】:
标签: javascript reactjs loops react-native iteration