React-select 当没有选项与用户搜索值匹配时的默认值

React-select default value when no options match with the user search value

我有一个用于 react-select 的数组,如下所示

[{label:"blue",value:"blue"},{label:"green",value:"green"},{label:"other",value:"other"}]

当用户尝试搜索蓝色和绿色以外的其他选项(如棕色、紫色)时,其他选项应该显示在选项列表中,因此用户可以select "other"

有没有办法在react中实现这个功能-select

我想你要找的东西离 很近。

基本上使用这样的 filterOption 道具:

 filterOption = (option, inputValue) => {
    if (option.label === "Other") {
      const { options } = this.state;
      const result = options.filter(opt => opt.label.includes(inputValue));
      this.setState({ hasExtraValue: !result.length });
      return !result.length;
    }

    return option.label.includes(inputValue);
  };

这是符合您要求的 live example

上述解决方案的一个小问题。 搜索区分大小写。解决起来很简单:

filterOption = (option, inputValue) => {

const inputValueToUpperCase = inputValue.toUpperCase();

   if (option.label === "Other") {
      const { options } = this.state;
      const result = options.filter(opt => opt.label.toUpperCase().includes(inputValueToUpperCase));
      this.setState({ hasExtraValue: !result.length });
      return !result.length;
   }

   return option.label.toUpperCase().includes(inputValueToUpperCase);
}

这样就合适了。我希望能帮助到其他人。

这里有一个 live example 符合您的要求。