Убрать пункт, когда снят флажок - PullRequest
0 голосов
/ 26 февраля 2020

У меня есть флажок с парой элементов в нем, когда я нажимаю флажок, элемент будет добавлен в состояние под названием currentDevice, но когда я сниму флажок с элемента, он будет продолжать добавлять элемент, а не удалять его.

Как удалить элемент из состояния, когда я снял флажок. Я использую флажок реагировать родной элемент. Спасибо, прежде чем

Код:

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>
    )
  }

Ответы [ 2 ]

1 голос
/ 26 февраля 2020

изменить метод 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,
  })
};
0 голосов
/ 26 февраля 2020

Я нашел решение, вот код:

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

Кредит: Добавление отмеченных флажков в массив и удаление непроверенных - реагируйте на собственные

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...