我在react中创建了一个复选框过滤器,但我希望所有的选项在我开始过滤之前都是可见的,我该如何去做呢?



下面的代码的问题是,项目开始显示时,我点击然后在过滤器,我想做的是有所有可用的项目,然后当我开始过滤只有那些显示过滤。我应该在函数中还是在有条件的组件中解决这个问题?


// Data 
const data = [
{
id: 0,
poging: "Stoep",
},
{
id: 1,
poging: "Bon",
},
{
id: 2,
poging: "Bal",
},
];
// Filter function
function Filters() {
const [items, setItems] = useState(data);
const [filters, setFilters] = useState([]);
const clickFunction = (e) => {
const listItem = e.target.parentNode;
const list = listItem.parentNode;
// Loop through filter items
const filterList = Array.from(list.querySelectorAll("li"));
// Create new array based on the checked filters and change filter state
const newArray = filterList
.filter((item) => item.querySelector("input:checked"))
.map((item) => item.querySelector("label").textContent.toLowerCase());
setFilters(newArray);
};
// Filter list
<ul onChange={(e) => clickFunction(e)}>
<li>
<label htmlFor="stoep">Stoep</label>
<input type="checkbox" name="" id="stoep" />
</li>
<li>
<label htmlFor="bon">Bon</label>
<input type="checkbox" name="" id="bon" />
</li>
<li>
<label htmlFor="bal">Bal</label>
<input type="checkbox" name="" id="bal" />
</li>
</ul>
// Output of the items
<ul>
{items
.filter((item) => filters.includes(item.poging.toLowerCase()))
.map((item) => {
return (
<li key={item.id}>
<div>{item.poging}</div>
</li>
);
})}
</ul>

这看起来很简单-只需更改如下:

.filter((item) => filters.length === 0 || filters.includes(item.poging.toLowerCase()))

最新更新