useAntdTable.tsx
import { Table } from "antd";
import React, { ReactElement, useState } from "react";
interface ColumusProps {
title: string;
dataIndex: string;
render: (_: any, record: any) => ReactElement;
}
const useAntdTable = ({
columns,
data,
pagination,
}: {
columns: Array<ColumusProps>;
data: Array<any>;
pagination: any;
}) => {
const [selectedRows, setSelectedRows] = useState<any>();
const [isLoading, setIsLoading] = useState<boolean>(false);
const rowSelection = {
onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
console.log(
`selectedRowKeys: ${selectedRowKeys}`,
"selectedRows: ",
selectedRows
);
setSelectedRows(selectedRows);
},
};
const template = (
<Table
columns={columns}
dataSource={data}
loading={isLoading}
rowSelection={rowSelection}
pagination={pagination}
/>
);
return {
template,
selectedRows,
setIsLoading,
};
};
export default useAntdTable;
Home.tsx
import React, { ReactElement, useEffect, useState } from "react";
import useAntdTable from "../../hooks/useAntdTable";
import { Button, Space, Table, Tag } from "antd";
import type { ColumnsType } from "antd/es/table";
interface DataType {
key: string;
name: string;
age: number;
address: string;
tags: string[];
}
interface HomeProps {}
const Home: React.FC<HomeProps> = ({}): ReactElement => {
const columns: any = [
{
title: "Name",
dataIndex: "name",
key: "name",
},
{
title: "Age",
dataIndex: "age",
key: "age",
},
{
title: "Address",
dataIndex: "address",
key: "address",
},
{
title: "Tags",
key: "tags",
dataIndex: "tags",
render: (_: any, { tags }: any) => (
<>
{tags.map((tag: any) => {
let color = tag.length > 5 ? "geekblue" : "green";
if (tag === "loser") {
color = "volcano";
}
return (
<Tag color={color} key={tag}>
{tag.toUpperCase()}
</Tag>
);
})}
</>
),
},
{
title: "Action",
key: "action",
dataIndex: "Action",
render: (_: any, record: any) => (
<Space size="middle">
<a>Invite {record.name}</a>
<a>Delete</a>
</Space>
),
},
];
const [data, setData] = useState([
{
key: "1",
name: "John Brown",
age: 100,
address: "New York No. 1 Lake Park",
tags: ["nice", "developer"],
},
{
key: "2",
name: "Jim Green",
age: 42,
address: "London No. 1 Lake Park",
tags: ["loser"],
},
{
key: "3",
name: "Joe Black",
age: 32,
address: "Sidney No. 1 Lake Park",
tags: ["cool", "teacher"],
},
]);
const [pagination, setPagination] = useState({
pageSize: 10,
current: 1,
total: 100,
});
const { template, selectedRows, setIsLoading } = useAntdTable({
columns,
data,
pagination: {
...pagination,
onChange: (page: number, pageSize: number) => {
console.log(page);
setPagination({
...pagination,
current: page,
});
},
},
});
useEffect(() => {
console.log(pagination);
}, [pagination]);
const toSubmitRows = () => {
console.log(selectedRows);
setIsLoading(true);
};
return (
<div>
home
<div>
<Button onClick={toSubmitRows}>按钮</Button>
</div>
<div>{template}</div>
</div>
);
};
export default Home;
总结:custom hook就是一个函数,接收我们想传入的属性方法和template,return 出我们想用的数据(或state)和方法和template