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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值