所以我有这个数组作为我的状态:
["item-one","item-two", "item-three"]
现在我的网页上有这些项目:
Item One
Item Two
Item Three
Item Four
Item Five
如何根据阵列的状态过滤这些项目。所以当我过滤时,我会得到前三个项目?项目的html是这样的。
<div>
<label htmlFor="item-one">Item One</label>
<input type="checkbox" name="" id="item-one"/>
</div>
<div>
<label htmlFor="item-two">Item Two</label>
<input type="checkbox" name="" id="item-two"/>
</div>
<div>
<label htmlFor="item-three">Item Three</label>
<input type="checkbox" name="" id="item-three"/>
</div>
<div>
<label htmlFor="item-four">Item Four</label>
<input type="checkbox" name="" id="item-four"/>
</div>
<div>
<label htmlFor="item-five">Item Five</label>
<input type="checkbox" name="" id="item-five"/>
</div>
我应该使用地图函数还是最好的方法?
答案 0 :(得分:0)
您需要引用页面上的这些元素。从那里开始,在您的 render
函数中,您将根据您的 state
显示/隐藏这些元素。
示例:
// Assume `this.state` references you're array
const items = document.querySelector("div");
items.forEach(function (item) {
const input_elm = item.querySelector("input");
if (this.state.includes(input_elm.id)) {
item.style.display = "block";
} else {
item.style.display = "none";
}
});
注意:还有其他方法可以实现这一点。但我发现这是最简单的。