简体   繁体   English

使用 react-select 将值传递给 state

[英]Passing value to state using react-select

I'm new to react and trying to learn on my own.我是新来的反应并尝试自己学习。 I started using react-select to create a dropdown on a form and now I'm trying to pass the value of the option selected.我开始使用 react-select 在表单上创建下拉列表,现在我试图传递所选选项的值。 My state looks like this.我的 state 看起来像这样。

this.state = {
  part_id: "",
  failure: ""
};

Then in my render然后在我的渲染中

const {
  part_id,
  failure
} = this.state;

My form looks has 2 fields我的表单看起来有 2 个字段

<FormGroup>
  <Label for="failure">Failure</Label>
  <Input
    type="text"
    name="failure"
    placeholder="Failure"
    value={failure}
    onChange={this.changeHandler}
    required
    />
  </FormGroup>
  <FormGroup>
  <Label for="part_id">Part</Label>
  <Select
    name="part_id"
    value={part_id}
    onChange={this.changeHandler}
    options={option}
  />
  </FormGroup>

the changeHandler looks like this changeHandler看起来像这样

changeHandler = e => {
  this.setState({ [e.target.name]: e.target.value });
};

The change handler works fine for the input but the Select throws error saying cannot read property name.更改处理程序对输入工作正常,但 Select 抛出错误说无法读取属性名称。 I went through the API docs and came up with something like this for the Select onChange我浏览了 API 文档并为 Select onChange 想出了这样的东西

onChange={part_id => this.setState({ part_id })}

which sets the part_id as a label, value pair.它将 part_id 设置为 label 值对。 Is there a way to get just the value?有没有办法获得价值? and also how would I implement the same with multiselect ?以及我将如何使用multiselect实现相同的功能?

The return of react-select onChange event and the value props both have the type as below react-select onChange 事件的返回和 value props 的类型如下

event / value :事件/价值

null | {value: string, label: string} | Array<{value: string, label: string}>

So what the error means is that you can't find an attribute of null (not selected), or any attributes naming as name (you need value or label )所以错误的意思是你找不到 null 的属性(未选择),或任何命名为name属性(你需要valuelabel

For multiple selections, it returns the sub-list of options.对于多项选择,它返回选项的子列表。

You can find the related info in their document您可以在他们的文档中找到相关信息

const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' },
];

Update更新

For your situation (single selection)适合您的情况(单选)

  • option having type as above具有上述类型的选项
const option = [
  {value: '1', label: 'name1'},
  {value: '2', label: 'name2'}
]
  • state save selected value as id状态将选定的value保存为id
changeHandler = e => {
  this.setState({ part_id: e ? e.value : '' });
};
  • pick selected option item via saved id通过保存的id选择选定的选项项目
  <Select
    name="part_id"
    value={option.find(item => item.value === part_id)}
    onChange={this.changeHandler}
    options={option}
  />

For multiple selections对于多项选择

  • state save as id array状态保存为 id 数组
changeHandler = e => {
  this.setState({ part_id: e ? e.map(x => x.value) : [] });
};
  • pick via filter通过过滤器选择
  <Select
    isMulti // Add this props with value true
    name="part_id"
    value={option.filter(item => part_id.includes(item.value))}
    onChange={this.changeHandler}
    options={option}
  />

onChange function is a bit different in react-select react-select onChange函数有点不同

It passes array of selected values, you may get first one like它传递选定值的数组,您可能会得到第一个像

 onChange={([selected]) => {
    // React Select return object instead of value for selection
    // return { value: selected };
    setValue(selected)
 }}

I have tried the above solutions but some of these solutions does update the state but it doesn't gets rendered on the Select value instantly.我已经尝试了上述解决方案,但其中一些解决方案确实更新了 state 但它不会立即呈现在 Select 值上。

Herewith a demo example:附上一个演示示例:

this.state = {
          part_id: null,
        };

handleUpdate = (part_id) => {
    this.setState({ part_id: part_id.value }, () =>
        console.log(`Option selected:`, this.state.part_id)
    );
};

const priceOptions = [
    { value: '999', label: 'Item One' },
    { value: '32.5', label: 'Item Two' },
    { value: '478', label: 'Item Three' }
]

<Select
    onChange={this.handleUpdate}
    value={priceOptions.find(item => item.value === part_id)}
    options={priceOptions}
    placeholder={<div>Select option</div>}
/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM