React

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > React > antd autocomplete二次封装

基于antd的autocomplete的二次封装查询示例

作者:点墨

这篇文章主要为大家介绍了基于antd的autocomplete的二次封装查询示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

正文

基于antd的autocomplete进行二次封装,用于后端实时查询数据

autocomplete.js

import React, { useEffect, useState } from "react";
import { useDebounceFn } from "ahooks";
import { AutoComplete as AntdAutoComplete } from "antd";
import lodash from "lodash";
import protoTypes from "prop-types";
function EndAutoComplete(props) {
    const { value: propValue, onChange: propOnChange, defaultOptionsMap, fetchData, ...otherProps } = props;
    const [value, setValue] = useState(propValue);
    const [options, setOptions] = useState();
    const [optionsMap, setOptionsMap] = useState({});
    //初始化value
    useEffect(() => {
        if (defaultOptionsMap) {
            setValue(defaultOptionsMap[propValue]);
        }
    }, [defaultOptionsMap])
    //更新options map
    useEffect(() => {
        if (lodash.isArray(options)) {
            let newOptionMap = {};
            options.forEach(item => {
                const { value, label } = item;
                newOptionMap[label] = value;
            })
            setOptionsMap(newOptionMap);
        }
    }, [options])
    const _handleSearch = value => {
        const promise = fetchData(value);
        if (promise && promise.then) {
            promise.then(data => {
                setOptions(data);
            }).catch(e => {
                console.error("AutoComplete Fetch Data Error", e)
                setOptions([]);
            })
        }
    }
    const { run: handleSearch } = useDebounceFn(_handleSearch, { wait: 500 });//防抖
    const onSearch = value => {
        if (!value.trim()) {
            setOptions([]);
            return;
        }
        if (lodash.isFunction(fetchData)) {
            handleSearch(value);
        }
    }
    const onChange = (value) => {
        if (lodash.isFunction(propOnChange)) {
            propOnChange(optionsMap[value] || -999999);
        }
        setValue(value);
    }
    const onSelect = (value, option) => {
        if (lodash.isFunction(propOnChange)) {
            propOnChange(value);
        }
        setValue(option.label);
    }
    return (
        <AntdAutoComplete
            options={options}
            onSearch={onSearch}
            onSelect={onSelect}
            onChange={onChange}
            value={value}
            {...otherProps}
        >
        </AntdAutoComplete>
    )
}
EndAutoComplete.prototype = {
    fetchData: protoTypes.func,//异步获取数据
    defaultOptionsMap: protoTypes.object,//用于键盘精灵初始化赋值
}
export default EndAutoComplete;

以上就是基于antd的autocomplete的二次封装查询键盘示例的详细内容,更多关于antd autocomplete的二次封装的资料请关注脚本之家其它相关文章!

阅读全文