【问题标题】:Remove item when unchecked checkbox取消选中复选框时删除项目
【发布时间】:2020-02-26 18:50:22
【问题描述】:

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

【问题讨论】:

    标签: javascript react-native checkbox


    【解决方案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,
      })
    };
    

    【讨论】:

      【解决方案2】:

      我找到了解决方案,代码如下:

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-05
        • 1970-01-01
        相关资源
        最近更新 更多