Antd Design Pro Components 是基于Antd Design 提供的一些高级功能的组件。以下是一个hooks + TS + Antd ProTable中获取选中的key的demo:
修改评论区的问题,谢谢不吝赐教~
1. 表格开启checkbox配置:rowSelection={rowSelection}
<ProTable<videoList>
......
rowSelection={rowSelection}
// 行键 这里设置什么 rowSelection获取的就是对应的值 比如:rowKey="id", 输出的[1, 2, 3, 4]
rowKey="id"
/>
2. 获取选中的key的hook:useRowSelection.ts
import { Key, useState } from "react";
export const useRowSelection = () => {
const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
const onChange = (value: Key[]) => {
setSelectedRowKeys(value)
}
return [
{
rowSelection: selectedRowKeys,
onChange: onChange,
},
{
selectedRowKeys
}
]
};
3. 完整的 demo.tsx
import { useRowSelection } from '@/utils/hooks/useRowSelection';
import {
ActionType,
PageContainer,
ProColumns,
ProTable,
} from '@ant-design/pro-components';
import { Button, Input, message } from 'antd';
import React, { useRef } from 'react';
const TableList: React.FC<unknown> = () => {
const actionRef = useRef<ActionType>();
const columns: ProColumns[] = [
{
title: '搜索内容',
key: 'keyword',
hideInTable: true,
renderFormItem: () => {
return <Input placeholder="名称" />;
},
},
{
title: '名称',
dataIndex: 'name',
search: false,
},
{
title: '时长',
dataIndex: 'time',
search: false,
},
{
title: '格式',
dataIndex: 'type',
search: false,
},
{
title: '创建时间',
key: 'showTime',
dataIndex: 'createTime',
search: false,
},
{
title: '操作',
valueType: 'option',
render: () => <Button type='link'>查看</Button>
},
];
const [rowSelection, { selectedRowKeys }] = useRowSelection();
// 模拟接口数据
const fetchVideoList = async () => {
return [
{
id: 1,
name: "霸王别姬",
time: "171分钟",
type: "mp4",
createTime: "2022-10-21",
},
{
id: 2,
name: "霸王别姬",
time: "171分钟",
type: "mp4",
createTime: "2022-10-21",
},
{
id: 3,
name: "霸王别姬",
time: "171分钟",
type: "mp4",
createTime: "2022-10-21",
},
{
id: 4,
name: "霸王别姬",
time: "171分钟",
type: "mp4",
createTime: "2022-10-21",
}
]
}
return (
<PageContainer
header={{
title: 'CRUD 示例',
}}
footer={[
<Button
key="save"
type='primary'
onClick={() => {
message.success({ content: `选中的key: ${selectedRowKeys?.toString()}` })
// 选中的key: 1,2,3,4
}}
>提交</Button>
]}
>
<ProTable
columns={columns}
actionRef={actionRef}
request={async () => {
try {
// 获取参数接口
const data = await fetchVideoList();
// 返回的参数中必须有 success 和 data, 且success 是 Boolean, data 是array
return {
success: true,
data
}
} catch (e) {
return {
success: false,
data: []
}
}
}}
// 开启checkbox 进行批量操作
rowSelection={rowSelection}
// 行键 这里设置什么 rowSelection获取的就是对应的值 比如:rowKey="id", 输出的[1, 2, 3, 4]
rowKey="id"
headerTitle="列表"
/>
</PageContainer>
);
};
export default TableList;