【问题标题】:React-select {creatable} to work with user typed entry as only shows no optionsReact-select {creatable} 与用户输入的条目一起工作,因为只显示没有选项
【发布时间】:2019-08-21 17:00:40
【问题描述】:

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

我已经为引导表制作了附加组件。我可以像使用 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

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

【问题讨论】:

    标签: javascript react-select


    【解决方案1】:

    原来我有这个:

    import CreatableSelect from 'react-select';
    

    我需要这个:

    import CreatableSelect from 'react-select/creatable';
    

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

    【讨论】:

      【解决方案2】:

      您需要在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数组的末尾。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-05
        • 1970-01-01
        • 1970-01-01
        • 2022-12-03
        • 1970-01-01
        相关资源
        最近更新 更多