【问题标题】:react-select: Automatically suggest "other" option when you have no options for the searchreact-select:当您没有搜索选项时自动建议“其他”选项
【发布时间】:2021-07-02 19:47:48
【问题描述】:

我的表单上有一个可搜索的下拉字段,用户可以在其中进行研究并正常选择。

我需要的是,如果他键入一个不存在的选项,建议他选择“其他”选项。

“其他”选项已经存在,我只是不知道如何自动建议它。

我见过noOptionsMessage,但它对我没有用,我需要你自动建议该选项。

你能帮帮我吗?谢谢。

【问题讨论】:

    标签: reactjs select dropdown options react-select


    【解决方案1】:

    有一个名为 filterOption 的 props 可以自定义您希望在用户输入输入时如何过滤您的选项,但它只能过滤单个选项并且缺少其他选项的上下文。

    因此,要在没有可用选项时显示“其他”选项,您必须:

    • 禁用默认选项过滤器,以免与您的自定义过滤器混淆。
    • 控制选项状态。
    • 过滤掉用户类型的选项并更新选项状态。

    下面是一个例子来说明我的意思:

    import Select, { createFilter } from "react-select";
    
    const filterOption = createFilter({});
    
    const allOptions = [
      { value: "chocolate", label: "Chocolate" },
      { value: "strawberry", label: "Strawberry" },
      { value: "vanilla", label: "Vanilla" }
    ];
    const otherOption = { value: "other", label: "Other" };
    
    export default function App() {
      const [options, setOptions] = useState(allOptions);
      const filterAllOptions = (rawInput: string) => {
        const filteredOptions = allOptions.filter((o) => filterOption(o, rawInput));
    
        if (filteredOptions.length === 0) {
          filteredOptions.push(otherOption);
        }
    
        setOptions(filteredOptions);
      };
    
      return (
        <Select
          options={options}
          filterOption={() => true} // disable the default option filter
          onInputChange={(e) => filterAllOptions(e)}
        />
      );
    }
    

    现场演示

    【讨论】:

    • 这太棒了,谢谢@NearHuscarl!有没有办法添加 noOptionsMessage 以及显示这些“其他”选项?我试过这样的 -> &lt;Select options={options} filterOption={() =&gt; true} onInputChange={(e) =&gt; filterAllOptions(e)} components={{ NoOptionsMessage: function NoOptionsMessage() { return &lt;div&gt; custom message &lt;/div&gt;; }, }} /&gt; 但这并没有显示未找到的消息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 2011-07-13
    • 1970-01-01
    相关资源
    最近更新 更多