【发布时间】:2021-10-12 21:12:22
【问题描述】:
我需要在 React 中使用输入过滤器。我有一个活动列表,需要像图片上的过滤器一样过滤它们。如果未选中图标,则不应显示具有这些类型活动的操作。它有效。
当我使用输入过滤器并写信时它工作的问题。但是当我一个字母一个字母地删除时,什么都没有改变。
我知道问题是我在状态中写了结果。并且状态发生了变化。但是如何正确地重写它。
const [activities, setActivities] = useState(allActivities);
const [value, setValue] = useState(1);
const [checked, setChecked] = useState<string[]>([]);
const switchType = (event: React.ChangeEvent<HTMLInputElement>)=> {
const currentIndex = checked.indexOf(event.target.value);
const newChecked = [...checked];
if (currentIndex === -1) {
newChecked.push(event.target.value);
} else {
newChecked.splice(currentIndex, 1);
}
//function that shows activities if they are checked or unchecked
setChecked(newChecked);
const res = allActivities.filter(({ type }) => !newChecked.includes(type));
setActivities(res);
};
//shows input filter
const inputSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
const foundItems = activities.filter(
(item) => item.activity.indexOf(event.target.value) > -1
);
setActivities(foundItems);
};
//shows participants filter
const countSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
setValue(Number(event.target.value));
const participantsSearch = allActivities.filter(
(item) => item.participants >= event.target.value
);
setActivities(participantsSearch);
};
这是渲染部分
<Input
onChange={inputSearch}
startAdornment={
<InputAdornment position="start">
<SearchIcon />
</InputAdornment>
}
/>
<Input
onChange={countSearch}
type="number"
value={props.value}
startAdornment={
<InputAdornment
position="start"
className={classes.participantsTextField}
>
<PersonIcon />
</InputAdornment>
}
/>
【问题讨论】: