React-select {creatable} 与用户输入的条目一起使用,因为只显示没有选项

React-select {creatable} to work with user typed entry as only shows no options

react-select CreatableSelect 的问题不允许创建

我已经为 bootstrap table 制作了附件。我可以像使用 Select 一样查看我的硬编码标签,但是我无法让 Creatable 部分为用户输入新选项工作。我刚得到标签没有选项。

我试图将新输入添加到汽车数组并打印到控制台,但无法弄清楚。

import CreatableSelect from 'react-select';

const cars = [
  { label: "audi", value: 1 },
  { label: "bmw", value: 2 },
  { label: "ford", value: 3 },
  { label: "VW", value: 4 },
];

const selectOption = () => (
  <div className="app">
    <div className="container">
      <CreatableSelect
         options={cars} 
         placeholder={"check and enter new car name here"}
         isClearable
         onChange={(opt, meta) => console.log(opt, meta)}
      />
    </div>
  </div>
);

export default selectOption

我希望它在输入不在下拉列表中的选项时显示创建选项并将其添加到汽车数组

您需要在 Constructor 中初始化 this.state.cars={initialCarOption}。然后,您需要在 render 方法中执行以下操作:

return (
      <CreatableSelect
        options={this.state.cars}
        placeholder={"check and enter new car name here"}
        isClearable
        onChange={(opt, meta) =>
          this.setState({ cars: this.state.cars.slice().concat(opt) })
        }
      />
    );

这样,当用户输入一个新值时,该值将添加到 this.state.cars 中,并且会通过 options={this.state.cars}options 下拉列表中显示。

您可以在此处查看示例:https://codesandbox.io/s/react-codesandboxer-example-2rbl7。在沙盒中,一旦您添加了一个值,它将被添加到 options 数组的末尾。

原来我有这个:

import CreatableSelect from 'react-select';

我需要这个:

import CreatableSelect from 'react-select/creatable';

现在一切正常! 谢谢你的帮助:)