使 react-select 选项不可搜索

Make react-select option unsearchable

我正在使用 react-select,其中一个选项的名称和值为 not set,另一个选项的名称和值为 notification。这意味着我的选项数组看起来像这样(尽管有更多选项):

const options = [
  {
    label: '',
    value: 'not set'
  },
  {
    label: 'Notification',
    value: 'notification'
  }
];

因此,当用户寻找通知选项时,他们通常只键入 not,然后显示的是空白选项。

希望这个选项在有人只是翻阅它(使用箭头键)时显示在下拉菜单中,但是有没有办法我可以阻止某些选项在搜索中显示?也许我可以在选项中包含一个密钥?

我推荐你使用道具filterOption来达到你的目的。查看更多使用方法here

您可以决定仅按 label 而不是 value 进行过滤,或者为每个可搜索选项添加一个关键字,如下所示:

const options = [
  {
    label: '',
    value: 'not set',
    searchable: false
  },
  {
    label: 'Notification',
    value: 'notification',
    searchable: true
  }
];

// your custom filterOption function
 filterOption = ({ label, value, data }, string) => {
    if (string && data.searchable) {
      return label.includes(string) || value.toString().includes(string);
    } else {
      return true;
    }
  };