1.引入Ant Design Table相关组件:
import React, {useEffect, useState} from 'react';
import {Button, message, Table} from "antd";
import {ColumnsType} from "antd/es/table";
2.定义表格的列
const columns: ColumnsType<API.User> = [
{
title: 'Id',
dataIndex: 'id',
key: 'id',
},
{
title: '账号',
dataIndex: 'userAccount',
key: 'userAccount',
},
{
title: '昵称',
dataIndex: 'userName',
key: 'userName',
},
{
title: '头像',
key: 'userAvatar',
dataIndex: 'userAvatar',
},
{
title: '角色',
key: 'userRole',
dataIndex: 'userRole',
}, {
title: '创建时间',
key: 'createTime',
dataIndex: 'createTime',
},
{
title: '操作',
key: 'action',
render: (txt, record, index) =>{
return (
<div>
<Button type="primary" size="small">编辑</Button>
<Button type="primary" size="small">删除</Button>
</div>
)
}
},
];
3.从后端获取数据进行渲染,Table及分页相关参数可以参考https://ant-design.antgroup.com/components/table-cn
const Manage: React.FC = () => {
const initSearchParams = {
page: 1,
pageSize: 10,
};
const [searchParams, setSearchParams] = useState<API.UserQueryRequest>({...initSearchParams});
const [userList, setUserList] = useState<API.User[]>();
const [total, setTotal] = useState<number>(0);
const loadData = async (page: any, pageSize: any) => {
try {
searchParams.pageSize = pageSize ?? 10;
searchParams.current = page ?? 1;
const res = await listUserByPageUsingPost(searchParams);
if (res.data) {
setUserList(res.data.records ?? []);
setTotal(res.data.total ?? 0);
} else {
message.error("获取用户列表失败");
}
} catch (e: any) {
message.error("获取用户列表失败," + e.message);
}
};
useEffect(() => {
loadData();
}, [searchParams]);
return (
<Table
rowKey={"id"}
pagination={{
total: total,
pageSizeOptions: [10, 20, 50, 100],
onChange: loadData,
showTotal: total => `共${total}条记录 `,
defaultPageSize: 10,
defaultCurrent: 1,
position: ['bottomRight'],
size: 'small',
showSizeChanger: true,
showQuickJumper: true,
}}
style={{marginTop: 20}}
columns={columns}
dataSource={userList}/>
);
};