特性
- 支持 focus 时即发起请求获取用户列表
- 输入时 debounce 防抖
- 选中后以 tag 形式展示选项,这次点击 x 删除
- 搜索结果中若包含已选项会高亮
- 支持设置指定选项 disabled
一、具体代码
在 Antd - Select -搜索用户 demo 中给出了具体代码:
import React, {
useMemo, useRef, useState } from 'react';
import {
Select, Spin } from 'antd';
import type {
SelectProps } from 'antd';
import debounce from 'lodash/debounce';
export interface DebounceSelectProps<ValueType = any>
extends Omit<SelectProps<ValueType | ValueType[]>, 'options' | 'children'> {
fetchOptions: (search: string) => Promise<ValueType[]>;
debounceTimeout?: number;
}
function DebounceSelect<
ValueType extends {
key?: string; label: React.ReactNode; value: string | number } = any,
>({
fetchOptions, debounceTimeout = 800, ...props }: DebounceSelectProps<ValueType>) {
const [fetching, setFetching] = useState(false);
const [options, setOptions] = useState<ValueType[]>([]);
const fetchRef = useRef(0);
const debounceFetcher = useMemo(() => {