antd 封装select输入后自动搜索 显示option 组件

antd 封装select输入后自动搜索 显示option 组件_第1张图片

框架自带的 自动搜索 有BUG 用 select 组件 封装

子组件

import _ from 'lodash'
import { Select, Empty } from 'antd';
import React, { useState, useEffect } from 'react';
import { PeopleDropList } from '@/services/admin';

const SelectRemoteSearch = (props) => {

  const { onSelect, requestData = {}, placeholder } = props
  const { Option } = Select;
  const [peopleDropList, setPeopleDropList] = useState([]);

  const fetch = (value) => {
    PeopleDropList({
      QueryClause: value,
      ...requestData,
    }).then(res => {
      if (res) {
        if (res.ReturnCode == 1001) {
          let list = [];
          !!res.PeopleDropList && res.PeopleDropList.map(item => {
            list.push({
              Label: `${item.PersonName} ${item.Label ? '(' + item.Label + ')' : ''}`,
              Value: item.Value,
              StaffCode: item.StaffCode,
              Id: `${item.PersonName} ${item.Label ? '(' + item.Label + ')' : ''}`,
              Function: item.Function,
              Email: item.Label,
              Name: item.PersonName,
              Level: item.Level,
            });
          });
          setPeopleDropList(list);
        };
      };
    })
  };

  const handleChange = (value, option) => {
    onSelect && onSelect(value, option);
  };

  const handleSearch = (value) => {
    searchDebounce(value);
  };

  const searchDebounce = _.debounce(fetch, 500); // 防抖

  return (
    <Select
      showSearch
      allowClear
      showArrow={true}
      filterOption={false}
      onChange={handleChange}
      onSearch={handleSearch}
      style={{ width: '100%' }}
      placeholder={placeholder}
      defaultActiveFirstOption={false}
      notFoundContent={null}
    >
      {!!peopleDropList && peopleDropList.map(item => {
        return <Option value={item.Value} key={item.Value} optiondata={item}>{item.Label}</Option>;
      })}
    </Select>
  );
};

export default SelectRemoteSearch;

父组件
import SelectRemoteSearch from '@/components/SelectRemoteSearch';


  const onSelect = (value, option) => {
    if (!!option) {
      let data = option.optiondata;
      form.setFieldsValue({
        StudentName: data.Name,
        Email: data.Email,
        Function: data.Function,
        Level: data.Level,
      });
      setStaffCode(data.StaffCode);
    } else {
      form.setFieldsValue({
        StudentName: '',
        Email: '',
        Function: '',
        Level: '',
      });
      setStaffCode('');
    };
  };

			 <Form.Item
                label="Name"
                name='StudentName'
                rules={[{ required: true, message: 'Please Select Name' }]}
              >
                <SelectRemoteSearch
                  placeholder={'Name'}
                  onSelect={onSelect}
                />
              </Form.Item>
···

你可能感兴趣的:(react,react.js,javascript,前端)