跳到主要内容

Select 组件

赋值问题

原理

数据回填的时候类型要和 option 里面的 value 一致 当我 value 值为number时

回填数据:string, 显示错误

回填数据:number, 显示正确

试一试

实现拼音搜索

原理

通过 Select 中的 filterOption 结合 pinyin-match 这个库去实现拼音搜索

代码实现


// 引用
import Pinyin from "pinyin-match"; // 拼音匹配

——————————————————————————————————————————————————

const [Options, setOptions] = useState<
{ label: string; value: number | string }[] | []
>([
{ label: "小明(1)", value: 1 },
{ label: "小红(2)", value: 2 },
{ label: "小黄(3)", value: 3 },
{ label: "小叶(4)", value: 4 },
{ label: "小绿(5)", value: 5 },
{ label: "小灰(6)", value: 6 },
]);

const filterFun = (input: any, option: any) => {
return (
(option?.label).includes(input) ||
(option?.value).toString().includes(input) ||
Pinyin.match(option?.label, input)
);
};

return (
<Select
style={{ width: 200 }}
allowClear
showSearch
filterOption={filterFun}
options={Options}
/>
);

试一试