react antd select组件添加全选功能

1、需求

最近遇到一个需求,一张表单中需要有个下拉框,antd官网中有相应的Select组件,但是由于数据比较多,用户需要一个全选的需求。即点击全选下拉框数据全部选中,再次点击取消全选即选中的数据清空。然后数据一条一条点击完后全选框会被选中,反之不会被选中。

2、实现代码

import React from 'react';
import 'antd/dist/antd.css';
import './index.css';
import { Form, Select, Checkbox, Divider } from 'antd';

class Domo extends React.Component {
  formRef = React.createRef();
  constructor(props) {
    super(props);
    this.state = {
      selectStatus: false,
      selectData: '',
    };
  }

  render() {
    const data = [];
    for (let i = 0; i < 12; i++) {
      const value = `${i.toString(36)}${i}`;
      data.push({
        label: value,
        value
      });
    }
    const { selectStatus } = this.state;
    return (
      <>
        <Form ref={this.formRef}>
          <Form.Item name="selectOptions">
            <Select
              mode="multiple"
              placeholder="please choose"
              allowClear
              options={data}
              onChange={(value) => {
                this.setState({ selectData: value.join(',') });
                if (value.length === data.length) {
                  this.setState({ selectStatus: true });
                } else {
                  this.setState({ selectStatus: false });
                }
              }}
              dropdownRender={(menu) => (
                <>
                  <div
                    style={{ padding: '4px 8px 8px 12px', cursor: 'pointer' }}
                  >
                    <Checkbox
                      checked={selectStatus}
                      onChange={(e) => {
                        const a = data.map((item) => item.value);
                        if (e.target.checked) {
                          this.setState({
                            selectStatus: true,
                            selectData: a.join(','),
                          });
                          this.formRef.current.setFieldsValue({
                            selectOptions: data?.map((item) => item.value),
                          });
                        } else {
                          this.setState({
                            selectStatus: false,
                            selectData: '',
                          });
                          this.formRef.current.setFieldsValue({
                            selectOptions: [],
                          });
                        }
                      }}
                    >
                      全选
                    </Checkbox>
                  </div>
                  <Divider style={{ margin: '0' }} />
                  {menu}
                </>
              )}
            ></Select>
          </Form.Item>
        </Form>
        <h3 style={{ position: 'fixed', bottom: '100px' }}>
          选择的数据是:{this.state.selectData}
        </h3>
      </>
    );
  }
}

export default Domo;

3、效果预览

react antd select组件添加全选功能

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