React table 自定义泛型
【前言】一个项目中多个功能需要用table进行展示,每个table展示的列不一样,数据不一样,功能是一样的。比如功能有:每列可进行排序、每列可根据自己输入搜索、每个table可导出当前可看数据和所有数据、每个table可选择展示某些列等功能。若是每个页面都写一遍这些代码,会造成代码冗余,所以以泛型的方式来实现复用。
1、table 泛型组件
// umi3.x,antd4.x
import { Table } from 'antd';
import type { ColumnsType } from 'antd/lib/table';
import React from 'react';
type Props<T> = {
list: T[];// 数据列表
key1: string;// key键
key2?: string;// 当数据中没有唯一键的时候,可以key1+key2当成键
columns: ColumnsType<T>;// 列
onChange?: () => void;// change事件
};
function TestTGeneric<T extends object = any>(props: Props<T>) {
return (
<Table<T>
columns={props?.columns}
dataSource={props?.list}
rowKey={(record: T) => (props.key2 ? record[props.key1] + record[props.key2] : record[props.key1])}
scroll={{ x: 'max-content', y: 240 }}
size="small"
onChange={props?.onChange}
className="acss-small-table"
pagination={{
showQuickJumper: true,
showSizeChanger: true,
size: 'small',
}}
/>
);
}
export default TestTGeneric;
2、组件中使用
import React from 'react';
import TestTGeneric from './testTGeneric';
type aabb = {
id: number;
name: string;
};
type ccdd = {
id: number;
name: string;
address: string;
sex: string;
birth: string;
};
const TestT = () => {
const list: aabb[] = [
{ id: 1, name: 'xxx' },
{ id: 2, name: 'sge' },
{ id: 3, name: 'gweg' },
];
const listCcdd: ccdd[] = [
{ id: 1, name: '张三', address: '重庆', sex: '男', birth: '1994-02-04' },
{ id: 1, name: '李四', address: '成都', sex: '男', birth: '1992-10-14' },
{ id: 3, name: '王五', address: '北京', sex: '男', birth: '1991-08-22' },
];
const columns = [
{
title: 'id',
dataIndex: 'id',
key: 'id',
},
{
title: 'name',
dataIndex: 'name',
key: 'name',
},
];
const columns2 = [
{
title: 'id',
dataIndex: 'id',
key: 'id',
},
{
title: 'name',
dataIndex: 'name',
key: 'name',
},
{
title: 'address',
dataIndex: 'address',
key: 'address',
},
{
title: 'sex',
dataIndex: 'sex',
key: 'sex',
},
{
title: 'birth',
dataIndex: 'birth',
key: 'birth',
},
];
return (
<>
<TestTGeneric<aabb> list={list} columns={columns} key1="id" />
<TestTGeneric<ccdd> list={listCcdd} columns={columns2} key1="id" key2="name" />
</>
);
};
export default TestT;