/DropdownTable

下拉表格组件(支持搜索与分页)

Primary LanguageTypeScript

dropdown-table


下拉列表选择框(带分页、搜索)v0.0.8新增Size参数 为保持与Select尽可能一致

修复无antd项目也可以使用该组件,新增size,open参数


Installation

yarn add dropdown-table
// or
npm i dropdown-table

01.gif 02.gif 03.gif

DropdownTable

API

NameDescriptionTypeDefault
columnstable列配置ColumnsType<any>--
mode单选 多选"radio" | "checkbox"radio
placeholder选择框默认文本string--
optionValueProp选择框的valuestringvalue
optionLabelProp回填到选择框的 Option 的属性值,默认是 Option 的子元素。 比如在子元素需要高亮效果时, 此值可以设为 valuestringlabel
searchPlaceholder搜索框默认文本string--
limit限制最多选择几个number--
onChangevalue 变化时,调用此函数(value: string[]) => void--
dropdownStyle下拉框样式CSSProperties--
defaultOptions设置默认选项,在需要回填时使用{ value: string; label: string; }[]--
value设置值string[]--
tableProps下拉表的table的参数props{ [key: string]: any; dataSource: T[]; loading: boolean; onChange?: (pagination?: TablePaginationConfig, filters?: any, sorter?: any) => void; pagination?: false | TablePaginationConfig; }--
onSearch搜索时调用此函数(keyword: string) => void--
disabled是否禁用boolean--
disableKeyscell禁用的keysstring[]--
isHiddenSearchBar是否隐藏搜索栏boolean--
onSelect选择回调函数(value: string[], data: T[], record: T | T[]) => void--
maxTagCount最多显示多少个 tag,响应式模式会对性能产生损耗number | "responsive"1
allowClear支持清除booleantrue
showArrow是否显示下拉小箭头booleantrue
size选择框大小SizeType--
open是否展开下拉框boolean--

Demo:

import React from 'react';
import { DropdownTable } from 'DropdownTable';
import { useAntdTable } from 'ahooks';
import { Button, Form, message } from 'antd';
import { useState } from 'react';
import 'antd/dist/antd.css';

const columns = [
  {
    title: '用户名',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
  },
];

const names = ['张', '李', '陈', '荀', '诸葛', '牛', '刘'];
const dataSource: { name: string; id: string }[] = [];
for (let i = 0; i < 20; i++) {
  const index = Math.floor(Math.random() * names.length);
  dataSource.push({
    name: `${names[index]}${i + 1}`,
    id: `${i + 1}`,
  });
}

const getData = (current: number, pageSize: number, searchKey?: string) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const start = (current - 1) * pageSize;
      const array: { name: string; id: string }[] = [];

      if (searchKey) {
        array.push(...[...dataSource].filter((rs) => rs.name.indexOf(searchKey) !== -1));
        if (array.length > 5) {
          resolve({
            total: array.length,
            list: [...array].splice(start, pageSize),
          });
        } else {
          resolve({
            total: array.length,
            list: array,
          });
        }
      } else {
        array.push(...[...dataSource].splice(start, pageSize));
        resolve({
          total: 20,
          list: array,
        });
      }
    }, 1000);
  });
};

export default () => {
  const [form] = Form.useForm();

  const [searchKey, setSearchKey] = useState('');

  const { tableProps } = useAntdTable<
    {
      total: number;
      list: { name: string; id: string }[];
    },
    { name: string; id: string },
    { name: string; id: string }
  >(
    (rs) => {
      const { current, pageSize } = rs;
      console.log('res', rs);

      // console.log("current:", current, pageSize);
      return getData(current, pageSize, searchKey);
    },
    {
      refreshDeps: [searchKey],
      defaultPageSize: 5,
      formatResult: (res) => {
        return res;
      },
    },
  );

  return (
    <div className="custom-component-page">
      <div className="custom-component-page__demo">
        普通单选用法:
        <DropdownTable
          columns={columns}
          mode="radio"
          placeholder="点击选择用户"
          searchPlaceholder="请输入用户名或者姓名搜索"
          optionValueProp="id"
          optionLabelProp="name"
          onChange={(selectedKeys) => {
            console.log('selectedKeys:', selectedKeys);
          }}
          tableProps={{ ...(tableProps as any) }}
          dropdownStyle={{ minWidth: 360 }} // 设置下拉表最小宽度,此处设置width无效必须设置minWidth
        />
      </div>
      <div className="custom-component-page__demo">
        普通多选用法:
        <DropdownTable
          columns={columns}
          mode="checkbox"
          placeholder="点击选择用户"
          searchPlaceholder="请输入用户名或者姓名搜索"
          optionValueProp="id"
          optionLabelProp="name"
          onChange={(selectedKeys) => {
            console.log('selectedKeys:', selectedKeys);
          }}
          tableProps={{ ...(tableProps as any) }}
          dropdownStyle={{ minWidth: 360 }} // 设置下拉表最小宽度,此处设置width无效必须设置minWidth
        />
      </div>
      <div className="custom-component-page__demo">
        <Form
          onFinish={(values) => {
            console.log('values:', values);
            message.info(`获取到表单数据${JSON.stringify(values)}`);
          }}
          form={form}
          initialValues={{ table: ['3', '4'] }}
        >
          <Form.Item label="form设置初始值" name="table">
            <DropdownTable
              columns={columns}
              defaultOptions={[...dataSource]
                .map((rs) => {
                  return { value: rs.id, label: rs.name };
                })
                .splice(2, 2)}
              mode="checkbox"
              maxTagCount="responsive"
              placeholder="点击选择用户"
              searchPlaceholder="请输入用户名或者姓名搜索"
              optionValueProp="id"
              optionLabelProp="name"
              disableKeys={['1', '8']}
              onChange={(selectedKeys) => {
                console.log('selectedKeys:', selectedKeys);
              }}
              onSearch={(keyword) => {
                setSearchKey(keyword);
              }}
              tableProps={{ ...(tableProps as any) }}
              dropdownStyle={{ minWidth: 360 }} // 设置下拉表最小宽度,此处设置width无效必须设置minWidth
            />
          </Form.Item>
        </Form>
        <Button
          onClick={() => {
            form.submit();
          }}
        >
          提交
        </Button>
      </div>
    </div>
  );
};