反应选择下拉选项未正确存储 [英] react-select drop down choices not storing correctly

查看:53
本文介绍了反应选择下拉选项未正确存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 react-select 下拉菜单以允许用户选择多个选项在 A、B 和 C 之间.目前这适用于 UI,但当一个选项被取消选择时,它不会从数组中删除.谁能给我一些关于如何做到这一点的提示?(比如A、B、C都被选中了,那么A没有被选中,怎么才能把A从数组中去掉?)

var selection = [];常量选择 = [{ 值:'a',标签:'a' },{ 值:'b',标签:'b' },{ 值:'c',标签:'c' },];handleChange = (selectedChoice) =>{this.setState({ selectedChoice });for (var i = 0; i < selectedChoice.length; i++) {如果 (choice.indexOf(selectedChoice[i].value) == -1){choice.push(selectedChoice[i].value);}}}

然后,在代码中进一步调用 console.log(choice),在单击按钮时打印.后跟:

render(){返回 (<Div ClassName="box"><选择选项={选择}是多的值={this.state.selectedChoice}onChange={this.handleChange}/>

);}

push 和 pop 不起作用,因为选项可能在中间.

解决方案

您不需要另一个选择变量.您已经拥有 selectedChoice 状态,该状态将为您存储所有选定的值.

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

I'm using a react-select drop down to allow users to choose multiple options between A, B and C. Currently this works on the UI but when an option is de-selected, it is not removed from the array. Can anyone give me hints as to how this is done? (Example, A, B, and C are selected, then A is unselected, how can A be removed from the array?)

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

Then, further down in the code console.log(choice) is called, printing when a button is clicked. Followed by:

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

Push and pop won't work as the option could be in the middle.

解决方案

You don't need another choice variable.you already have selectedChoice state that will store all the selected value for you.

Working Solution: https://codesandbox.io/embed/0pr9yoo8l

这篇关于反应选择下拉选项未正确存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆