首页 > 解决方案 > 当没有选项与用户搜索值匹配时 React-select 默认值

问题描述

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

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

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

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

标签: reactjsreact-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);
  };

这是一个符合您要求的实时示例。


推荐阅读