react-select 下拉选项未正确存储

react-select drop down choices not storing correctly

我正在使用 react-select 下拉菜单以允许用户在 A、B 和 C 之间选择多个选项。目前这适用于 UI,但是当取消选择一个选项时,它不会从数组中删除。谁能给我提示这是如何完成的? (比如A、B、C被选中,然后A被取消选中,A怎么从数组中移除?)

var choice = [];
const choices = [
  { value: 'a', label: 'a' },
  { value: 'b', label: 'b' },
  { value: 'c', label: 'c' },
];          

handleChange = (selectedChoice) => {
  this.setState({ selectedChoice });
  for (var i = 0; i < selectedChoice.length; i++) {
    if (choice.indexOf(selectedChoice[i].value) == -1){
      choice.push(selectedChoice[i].value); 
    }
  }
}

然后,在代码的更下方调用 console.log(choice),在单击按钮时打印。紧随其后:

render(){
  return (
    <Div ClassName="box">
      <Select options={choices}
        isMulti
        value={this.state.selectedChoice}
        onChange={this.handleChange}
      />
    </Div>
  );
}

按下和弹出将不起作用,因为选项可能在中间。

您不需要其他选择 variable.you 已有 selectedChoice 状态将为您存储所有选定的值。

工作解决方案:https://codesandbox.io/embed/0pr9yoo8l