返回

在 React 中使用 Ant Design 的 Table 实现复杂的多选功能

前端

前言

在构建现代 Web 应用程序时,表格(Table)是至关重要的 UI 组件,用于组织和展示数据。在 React 应用中,Ant Design 提供了一个功能强大的 Table 组件,可轻松创建动态、可交互的表格。本文将深入介绍如何利用 Ant Design 的 Table 实现多个多选功能,包括全选、半选等高级选项。

功能展示和使用需求

需求 基于 Ant Design 实现的表格需要实现多个多选,互不影响,包括全选、半选等功能。(可自由扩展)

功能展示:

  • 全选:选择表格中的所有行。
  • 半选:选择部分行,但不包括所有行。
  • 单选:选择单行。
  • 取消选择:取消对任何行的选择。

封装代码

步骤 1:安装 Ant Design

npm install antd

步骤 2:创建基本表格

import { Table } from 'antd';

const columns = [
  { title: '姓名', dataIndex: 'name' },
  { title: '年龄', dataIndex: 'age' },
  { title: '地址', dataIndex: 'address' },
];

const data = [
  { name: '张三', age: 20, address: '北京' },
  { name: '李四', age: 25, address: '上海' },
  { name: '王五', age: 30, address: '广州' },
];

const BasicTable = () => <Table columns={columns} dataSource={data} />;

步骤 3:实现多选功能

import { Table, Checkbox } from 'antd';

const columns = [
  {
    title: '',
    dataIndex: 'selected',
    render: () => <Checkbox />,
  },
  { title: '姓名', dataIndex: 'name' },
  { title: '年龄', dataIndex: 'age' },
  { title: '地址', dataIndex: 'address' },
];

const data = [
  { name: '张三', age: 20, address: '北京', selected: false },
  { name: '李四', age: 25, address: '上海', selected: false },
  { name: '王五', age: 30, address: '广州', selected: false },
];

const MultipleSelectionTable = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const onSelectChange = (selectedRowKeys) => {
    setSelectedRowKeys(selectedRowKeys);
  };

  const rowSelection = {
    onChange: onSelectChange,
  };

  return (
    <Table
      columns={columns}
      dataSource={data}
      rowSelection={rowSelection}
    />
  );
};

完结:献给需要的朋友

通过逐步的代码讲解,我们成功地利用 Ant Design 的 Table 实现了多个多选功能,包括全选、半选等。这份指南为开发人员提供了在 React 应用中创建动态、可交互表格的全面解决方案。希望这篇文章能为你们带来帮助和启发。