一行代码让Antd Select支持首字母模糊搜索

790 阅读1分钟

前言

我在之前的文章中也做过Vue Element-select组件的二次封装,解决了性能问题,添加了拼音首字母搜索功能 此处。 这次又在捯饬Antd的Select了。

踩坑:鄙人之前以为Antd Select提供的自定义搜索方法和Element一样的,需要自己在里面写一大堆代码,输入的时候filter过滤、删除的时候还要还原原数组,仔细阅读文档发现Antd Select filterOption方法返回的是一个Boolean,如下图,我瞬间顿悟了

image.png

实现

一、安装依赖

和element-selecty用的同一个依赖此处

$ npm install pinyin-match --save
or
$ yarn add pinyin-match

pinyin-match找到目标会返回Array,找不到返回false,下面会用到。

二、在Select组件中使用

import PinyinMatch from "pinyin-match";
const Demo: React.FC = () => {
       const options = [
            { label: '张三', value: 1 },
            { label: '李四', value: 2 }
        ]
    return (
        <Select
            showSearch
            filterOption={(input, option) => {
                // 首字母、模糊搜索
                return PinyinMatch.match(option?.label as string, input) ? true : false
            }
            }
            options={options}
        >
        </Select >
    )
}
export default Demo

三、效果图

ezgif.com-gif-maker.gif