React + Antd 自定义Select选择框 全选、清空功能

实现代码

import React, { useState, useEffect } from 'react';
import { Select, Space, Divider, Button } from 'antd';

export default function AllSelect (props) {
  const {
    fieldNames, // 自定义节点labbel、value、options、grouLabel
    options, // 数据化配置选项内容,{label,value}[]

    value, // 指定当前选中的条目,多选时为一个数组
    onChange, // 选中option或input的value变化时
    ...restProps
  } = props;

  // console.log('AllSelect', mode);

  const [selectValue, setSelectValue] = useState([]);
  const [isShowAll, setIsShowAll] = useState(false);

  const selectAll = () => {
    let values = options.map(option => {
      return fieldNames.value
        ? option[fieldNames.value]
        : option.value || option;
    });
    setSelectValue(values);
    onChange(values);
  };

  const clearAll = () => {
    setSelectValue([]);
    onChange([]);
  };

  // 选中option或input的value变化时
  const handleChange = (values, option) => {
    console.log('handleChange', values);
    setSelectValue(values);
    onChange(values);
  };

  // 页面加载完成时调用
  useEffect(() => {
    if (props.mode) {
      setIsShowAll(true);
    } else {
      setIsShowAll(false);
    }
  }, []);

  return (
    <Select
      placeholder='请选择'
      fieldNames={fieldNames}
      value={selectValue}
      options={options}
      onChange={handleChange}
      dropdownRender={menu => (
        <>
          {menu}

          {isShowAll ? (
            <>
              <Divider style={{ margin: '8px 0' }} />
              <Space>
                <Button type='link' onClick={selectAll}>
                  全选
                </Button>
                <Button type='link' onClick={clearAll}>
                  清空
                </Button>
              </Space>
            </>
          ) : (
            ''
          )}
        </>
      )}
      {...restProps}
    ></Select>
  );
}

使用

import { useState } from "react";

export default function SelectDemo() {
  const { optionList, setOptionList } = useState([
    {
      id: 1,
      name: "律师",
    },
    {
      id: 2,
      name: "教师",
    },
    {
      id: 3,
      name: "厨师",
    },
    {
      id: 4,
      name: "会计",
    },
  ]);
  return (
    <AllSelect
      style={{ width: 300 }}
      options={optionList}
      mode="multiple"
      defaultValue={[]}
      maxTagCount="responsive"
      fieldNames={{ label: "name", value: "id" }}
    ></AllSelect>
  );
}

参考:
https://blog.csdn.net/likepoems/article/details/128549643
https://www.cnblogs.com/likepoems/p/17025233.html
https://blog.csdn.net/qq_41620887/article/details/129985339

你可能感兴趣的:(React,reactjs)