import { Table } from 'antd'; import { useImmer } from 'common/hooks/useImmer'; import { get } from 'utils/request'; import type { ColumnsType, TablePaginationConfig } from 'antd/es/table'; import { useState } from 'react'; import { AnyObject } from 'antd/es/_util/type'; interface Params { page?: number; pageSize?: number; } interface EasyTableProps<T, U> { url: string; columns: ColumnsType<U>; rowKey: string; callback: () => T; withoutPagination?: boolean | undefined; } type Res = { pageInfo: { totalItem: number }; list: [] }; const Index = <T, U extends AnyObject>(props: EasyTableProps<T, U>) => { const { url, columns, rowKey, callback, withoutPagination } = props; const [pag, setPag] = useImmer({ page: 1, pageSize: 10, }); const [loading, setLoading] = useState(false); const [tableInfo, setTableInfo] = useImmer({ dataSource: [], total: 0 }); const updateList = (params: Params) => { const page = params.page ? params.page - 1 : 0; const pageSize = params.pageSize ? params.pageSize : 10; if (!params.page) { setPag((item) => { item.page = 1; item.pageSize = 10; }); } const paramData = {}; Object.assign(paramData, { page, pageSize }, { ...callback() }); setLoading(true); get(url, paramData) .then((res: { data: Res }) => { if (withoutPagination && Array.isArray(res)) { setTableInfo((draft) => { draft.total = res.length; draft.dataSource = res as unknown as []; }); } else { setTableInfo((draft) => { draft.total = res.data.pageInfo.totalItem; draft.dataSource = res.data.list; }); } }) .finally(() => { setLoading(false); }); }; const onChange = (page: number, pageSize: number) => { if (pageSize !== pag.pageSize) { page = 1; } setPag((draft) => { draft.page = page; draft.pageSize = pageSize; }); updateList({ page: page, pageSize: pageSize }); }; const pagination = { total: tableInfo.total, current: pag.page, pageSize: pag.pageSize, showSizeChanger: true, showQuickJumper: true, pageSizeOptions: [10, 20, 50, 100], showTotal: (num: number) => `共 ${num} 条`, onChange: onChange, position: ['bottomCenter'], } as TablePaginationConfig; const EasyTable = () => ( <Table columns={columns} rowKey={rowKey} loading={loading} dataSource={tableInfo.dataSource} pagination={!withoutPagination ? pagination : false} /> ); return [EasyTable, updateList]; }; export default Index;
2023-08.11
有关columns:ColumnsType<MsgTable>
ColumnsType其实是import { ColumnsType } from 'antd/es/table';
export interface MsgTable { topic: string; queueId: string; brokerName: string; storeSize: number; bornHost: string; storeTime: number; storeHost: string; bornTime: number; messageId: string; keys: string; traceId: string; spanId: string; } 具体泛型依据你表格列名而来 注意⚠️:但是在之前antd 版本中table里面的columns有过ColumnsType<object>时候被我赶上用了 标签:内置,const,string,pageSize,number,draft,封装,page,useTable From: https://www.cnblogs.com/MDGE/p/17623181.html