首页
/ Ant Design 表格行选中事件处理机制解析

Ant Design 表格行选中事件处理机制解析

2025-04-29 02:43:19作者:滕妙奇

Ant Design 作为企业级 UI 设计语言和 React 实现,其 Table 组件提供了强大的行选择功能。本文将深入探讨如何利用 Ant Design Table 组件的行选择机制来处理用户交互事件。

核心概念:rowSelection 配置

Table 组件的行选择功能通过 rowSelection 属性实现,该属性接收一个配置对象,主要包含以下关键配置项:

  1. selectedRowKeys:当前已选中的行 key 数组,用于控制哪些行处于选中状态
  2. onChange:选中项发生变化时的回调函数
  3. type:选择类型,可选值为 'checkbox' 或 'radio'
  4. getCheckboxProps:自定义选择框的默认属性

实现原理

当用户在表格中进行行选择操作时,Table 组件内部会触发以下流程:

  1. 用户点击选择框或行区域
  2. 组件内部处理选择状态变化
  3. 调用 onChange 回调函数
  4. 更新 selectedRowKeys 状态
  5. 触发组件重新渲染

完整示例代码

import React, { useState } from 'react';
import { Table } from 'antd';

const SelectionTable = () => {
  const [selectedKeys, setSelectedKeys] = useState([]);
  
  const handleSelectionChange = (selectedRowKeys) => {
    console.log('选中行变化:', selectedRowKeys);
    setSelectedKeys(selectedRowKeys);
  };

  const selectionConfig = {
    selectedRowKeys: selectedKeys,
    onChange: handleSelectionChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
    ]
  };

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

  const dataSource = [
    { key: '1', name: '张三', age: 28, address: '北京市朝阳区' },
    { key: '2', name: '李四', age: 32, address: '上海市浦东新区' },
    { key: '3', name: '王五', age: 25, address: '广州市天河区' }
  ];

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

高级应用场景

1. 条件选择控制

可以通过 getCheckboxProps 实现基于行数据的条件选择控制:

const selectionConfig = {
  getCheckboxProps: (record) => ({
    disabled: record.age < 30, // 年龄小于30岁的行不可选
  }),
  // 其他配置...
};

2. 自定义选择菜单

Ant Design Table 提供了内置的选择菜单,可以通过 selections 配置自定义选择项:

const selectionConfig = {
  selections: [
    Table.SELECTION_ALL,
    Table.SELECTION_INVERT,
    Table.SELECTION_NONE,
    {
      key: 'odd',
      text: '选择奇数行',
      onSelect: (changeableRowKeys) => {
        const newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
          return index % 2 !== 0;
        });
        setSelectedKeys(newSelectedRowKeys);
      },
    },
  ],
  // 其他配置...
};

3. 跨页保持选择状态

当表格数据分页时,默认情况下切换页面会清空选择状态。如需保持选择状态,需要在数据加载时保留已选 key:

// 在获取新数据时保留已选key
const fetchData = () => {
  const newData = /* 获取新数据 */;
  const keptSelection = selectedKeys.filter(key => 
    newData.some(item => item.key === key)
  );
  setSelectedKeys(keptSelection);
};

性能优化建议

  1. 对于大数据量表格,建议使用 rowKey 指定唯一标识而非依赖默认的 key 属性
  2. 避免在 onChange 回调中执行复杂计算
  3. 考虑使用 useMemo 优化 rowSelection 配置对象
  4. 对于超大数据集,可以实现虚拟滚动来提升性能

Ant Design 的 Table 行选择功能经过精心设计,既满足了基础需求,又提供了足够的扩展性。通过合理配置,开发者可以轻松实现各种复杂的行选择交互场景。

登录后查看全文
热门项目推荐
相关项目推荐