我有一个包含几个项目的复选框,当我单击该复选框时,该项目将添加到状态为currentDevice的状态,但是当我取消选中该项目时,它将保持添加状态,而不是将其删除。
当我取消选中框时如何从状态中删除项目。我正在使用react-native-element复选框。谢谢你
代码:
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>
)
}
答案 0 :(得分:1)
将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,
})
};
答案 1 :(得分:0)
我找到了解决方案,这里是代码:
handleChange = (index, item) => {
let checked = [...this.state.checked];
checked[index] = !checked[index];
this.setState({ checked });
this.setState(previous => {
let currentDevice = previous.currentDevice;
let index = currentDevice.indexOf(item.bcakId)
if (index === -1) {
currentDevice.push(item.bcakId)
} else {
currentDevice.splice(index, 1)
}
return { currentDevice }
}, () => console.log(this.state.currentDevice));
}
信用:Adding checked checkboxes to an array and removing the unchecked ones - react native