AntDesignPro的ProTable核心功能全解析

目录

一、actionRef 核心作用

二、完整使用示例

三、关键 API 详解

四、高级功能实现

1. 跨组件调用

2. 联动表单提交

五、常见问题解决

问题1:ref 值为 null

问题2:多表格冲突

六、最佳实践


在 Ant Design Pro 的 ProTable 组件中,actionRef 是与表格交互的核心属性,允许从外部控制表格操作。以下是关于 actionRef 的详细解释和使用方法:

一、actionRef 核心作用

const actionRef = useRef<ActionType>();
<ProTable actionRef={actionRef} />

actionRef 提供了以下关键功能:

  1. 刷新数据​:actionRef.current?.reload()
  2. 重置状态​:actionRef.current?.reset()
  3. 获取参数​:actionRef.current?.getParams()
  4. 操作选中行​:actionRef.current?.clearSelected()

二、完整使用示例

import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import React, { useRef } from 'react';

interface UserItem {
  id: number;
  name: string;
  age: number;
}

const UserTable: React.FC = () => {
  // 1. 创建 ref 引用
  const actionRef = useRef<ActionType>();

  // 2. 列定义
  const columns: ProColumns<UserItem>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      hideInSearch: true,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      render: (dom) => <a>{dom}</a>,
    },
    {
      title: '年龄',
      dataIndex: 'age',
      valueType: 'digit',
    },
  ];

  return (
    <div>
      {/* 3. 外部操作按钮 */}
      <div style={{ marginBottom: 16 }}>
        <Button onClick={() => actionRef.current?.reload()}>刷新表格</Button>
        <Button onClick={() => actionRef.current?.reset()}>重置筛选</Button>
      </div>

      {/* 4. ProTable 集成 */}
      <ProTable<UserItem>
        actionRef={actionRef}
        rowKey="id"
        columns={columns}
        request={async (params) => {
          // 模拟请求数据
          const { current, pageSize, ...restParams } = params;
          const response = await fetch(`/api/users?page=${current}&size=${pageSize}`);
          return {
            data: response.list,
            success: response.success,
            total: response.totalCount,
          };
        }}
        rowSelection={{
          // 选中行管理
          onChange: (selectedRowKeys, selectedRows) => {
            console.log('选中行:', selectedRows);
          },
        }}
        tableAlertRender={({ selectedRowKeys }) => (
          <span>已选 {selectedRowKeys.length} 项</span>
        )}
        toolBarRender={() => [
          <Button 
            key="export" 
            onClick={() => {
              // 5. 获取当前筛选参数
              const params = actionRef.current?.getParams();
              exportData(params);
            }}>
            导出数据
          </Button>,
        ]}
      />
    </div>
  );
};

三、关键 API 详解

方法参数功能说明使用场景
reload()resetPageIndex?: boolean刷新表格数据数据更新后刷新
reloadAndReset()-重置分页后刷新表单提交后
reset()-重置筛选/排序清空搜索条件
clearSelected()-清除选中状态批量操作后
getParams()-获取当前参数导出/打印数据

四、高级功能实现

1. 跨组件调用
// 在外部组件中操作表格
const ExternalController = () => {
  const { tableRef } = useContext(TableContext);

  return (
    <Button onClick={() => tableRef.current?.reload()}>
      刷新用户表格
    </Button>
  );
};

// 在 ProTable 中通过 context 共享 ref
<TableContext.Provider value={{ tableRef: actionRef }}>
  <ProTable />
  <ExternalController />
</TableContext.Provider>
2. 联动表单提交
// 表单提交成功后刷新表格
const [form] = Form.useForm();

const handleSubmit = async () => {
  await addUser(form.getFieldsValue());
  message.success('添加成功');
  
  // 刷新表格并重置分页
  actionRef.current?.reloadAndReset();
  
  // 清除选中状态
  actionRef.current?.clearSelected();
};

五、常见问题解决

问题1:ref 值为 null

解决方案:​​ 确保在 useEffect 中正确访问

useEffect(() => {
  // 在组件挂载后操作
  if (actionRef.current) {
    actionRef.current.reload();
  }
}, []);
问题2:多表格冲突

解决方案:​​ 为每个表格创建独立 ref

const userRef = useRef<ActionType>();
const orderRef = useRef<ActionType>();

六、最佳实践

  1. 封装 hook 简化操作
const useTableActions = () => {
  const ref = useRef<ActionType>();
  
  return {
    ref,
    reload: () => ref.current?.reload(),
    reset: () => ref.current?.reset(),
    getParams: () => ref.current?.getParams() || {},
  };
}

// 使用
const { ref: userRef, reload } = useTableActions();
  1. TypeScript 增强类型
declare module '@ant-design/pro-table' {
  interface ActionType {
    // 添加自定义方法
    exportExcel: () => void;
  }
}

// 在 ProTable 中扩展
actionRef.current!.exportExcel = () => {
  exportToExcel(actionRef.current?.getParams());
};
  1. 操作状态管理
const [loading, setLoading] = useState(false);

<ProTable
  request={async (params) => {
    setLoading(true);
    try {
      const data = await fetchData(params);
      return data;
    } finally {
      setLoading(false);
    }
  }}
/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值