[英]React JS Toggle Selected Item
I'm using react hooks, state within my component.我在我的组件中使用了反应钩子 state。 A list of options is available to the user to select.
用户可以使用 select 的选项列表。 I need tokeep track of which options have been selected - see "selectedArr" in state.
我需要跟踪选择了哪些选项 - 请参阅 state 中的“selectedArr”。
Whilst this partially works, filtering the selectedArr is buggy and won't filter if I select the second item in the options first?虽然这部分有效,但过滤 selectedArr 是错误的,如果我 select 首先是选项中的第二项,则不会过滤? I don't understand why.
我不明白为什么。
How can I keep track of which options are selected and toggle an individual option?如何跟踪选择了哪些选项并切换单个选项?
Here is my code这是我的代码
const BarGraph = ({graphData, daysRange}) => {
const [optionsIndex, setOptionsIndex] = useState(0);
const [selectedArr, setSelectedArr] = useState([]);
const toggleActiveItem = (index) => {
//Update the option index
setOptionsIndex(index);
//Update selected options array
setSelectedArr([...selectedArr, index])
if(index === selectedArr[index]) {
//Prevent from adding multiple of the same index
setSelectedArr([...selectedArr])
//if index is equal to the selected array index
//removed the matched index from selected array
setSelectedArr(selectedArr.filter((i) => i !== index));
}
}
const toggleActiveItem = (index) => {
if(selectedArr.includes(index)){
setSelectedArr(selectedArr.filter((i) => i !== index))
} else {
setSelectedArr([...selectedArr, index])
}
setOptionsIndex(index)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.