使用 react-select 将值传递给状态

Passing value to state using react-select

我是新手,正在努力自学。我开始使用 react-select 在表单上创建下拉菜单,现在我试图传递选项 selected 的值。我的状态是这样的。

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

然后在我的渲染中

const {
  part_id,
  failure
} = this.state;

我的表单看起来有 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>

changeHandler 看起来像这样

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

更改处理程序对输入工作正常,但 Select 抛出错误提示无法读取 属性 名称。我浏览了 API 文档并为 Select onChange

想出了类似的东西
onChange={part_id => this.setState({ part_id })}

将 part_id 设置为标签、值对。有没有办法获得价值?以及我将如何使用 multiselect?

实现相同的功能

react-selectonChange事件的return和value属性的类型如下

事件/值

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

所以错误的意思是你找不到一个 null 的属性(未选择),或者任何命名为 name 的属性(你需要 valuelabel )

对于多项选择,return是选项的子列表。

您可以在他们的 document

中找到相关信息
const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' },
];

更新

根据您的情况(单选)

  • 具有上述类型的选项
const option = [
  {value: '1', label: 'name1'},
  {value: '2', label: 'name2'}
]
  • 状态保存选择 valueid
changeHandler = e => {
  this.setState({ part_id: e ? e.value : '' });
};
  • 通过已保存的选项选择选项id
  <Select
    name="part_id"
    value={option.find(item => item.value === part_id)}
    onChange={this.changeHandler}
    options={option}
  />

多选

  • 状态保存为id数组
changeHandler = e => {
  this.setState({ part_id: e ? e.map(x => x.value) : [] });
};
  • 通过过滤器选择
  <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 函数在 react-select

中有点不同

它传递选定值的数组,您可能会得到第一个像

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

我已经尝试了上述解决方案,但其中一些解决方案确实会更新状态,但不会立即在 Select 值上呈现。

附上演示示例:

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