我有一个带有几个项目的复选框,当我单击该复选框时,该项目将添加到状态为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>
    )
  }

最佳答案

将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,
  })
};

10-07 19:26
查看更多