react-select:当您没有搜索选项时,自动建议 "other" 选项
react-select: Automatically suggest "other" option when you have no options for the search
我的表单上有一个可搜索的下拉字段,用户通常会在其中进行研究和 selects。
我需要的是,如果他键入一个不存在的选项,建议他选择“其他”选项 select。
“其他”选项已经存在,只是不知道如何自动提示。
我看过noOptionsMessage
,但对我没用,我需要你自动建议选项。
你能帮帮我吗?谢谢
有一个名为 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)}
/>
);
}
现场演示
我的表单上有一个可搜索的下拉字段,用户通常会在其中进行研究和 selects。
我需要的是,如果他键入一个不存在的选项,建议他选择“其他”选项 select。
“其他”选项已经存在,只是不知道如何自动提示。
我看过noOptionsMessage
,但对我没用,我需要你自动建议选项。
你能帮帮我吗?谢谢
有一个名为 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)}
/>
);
}