gpt4 book ai didi

javascript - 未选中复选框时删除项目

转载 作者:行者123 更新时间:2023-12-02 21:39:07 26 4
gpt4 key购买 nike

我有一个带有几个项目的复选框,当我单击该复选框时,该项目将添加到名为 currentDevice 的状态,但是当我取消选中该项目时,它会保留添加项目而不是删除它。

当我取消选中该框时,如何从状态中删除项目。我使用 react native 元素复选框。先谢谢了

代码:

constructor(props) {
super(props)
this.state = {
currentDevice: [],
checked: []
}
}

handleChange = (index, item) => {
let checked = [...this.state.checked];
checked[index] = !checked[index];
this.setState({ checked });

this.setState({currentDevice: [...this.state.currentDevice, item.bcakId]})
}

renderFlatListDevices = (item, index) => {
return (
<ScrollView>
<CheckBox
title={item.label || item.bcakId}
checked={this.state.checked[index]}
onPress={() => {this.handleChange(index, item)}}
checkedIcon='dot-circle-o'
uncheckedIcon='circle-o'
checkedColor='#FFE03A'
containerStyle={styles.containerCheckBox}
textStyle={styles.textCheckBox}
/>
</ScrollView>
)
}

最佳答案

将handleChange方法更改为

const handleChange = (index, item) => {
const {currentDevice, checked} = state;
const found = currentDevice.some((data) => data === item.bcakId);
if (found) {
currentDevice.splice(
currentDevice.findIndex((data) => data === item.bcakId),
1
);
} else {
currentDevice.push(item.bcakId);
}
checked[index] = !checked[index];
this.setState({
currentDevice,
checked,
})
};

关于javascript - 未选中复选框时删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60411278/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com