目录
在 Ant Design Pro 的 ProTable 组件中,actionRef
是与表格交互的核心属性,允许从外部控制表格操作。以下是关于 actionRef
的详细解释和使用方法:
一、actionRef
核心作用
const actionRef = useRef<ActionType>();
<ProTable actionRef={actionRef} />
actionRef
提供了以下关键功能:
- 刷新数据:
actionRef.current?.reload()
- 重置状态:
actionRef.current?.reset()
- 获取参数:
actionRef.current?.getParams()
- 操作选中行:
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>();
六、最佳实践
- 封装 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();
- TypeScript 增强类型
declare module '@ant-design/pro-table' {
interface ActionType {
// 添加自定义方法
exportExcel: () => void;
}
}
// 在 ProTable 中扩展
actionRef.current!.exportExcel = () => {
exportToExcel(actionRef.current?.getParams());
};
- 操作状态管理
const [loading, setLoading] = useState(false);
<ProTable
request={async (params) => {
setLoading(true);
try {
const data = await fetchData(params);
return data;
} finally {
setLoading(false);
}
}}
/>