1.newColumns.tsx模块
// 隐藏表格头组件import { List, theme } from "antd";import { useState } from "react";import { AnyArray } from "immer/dist/internal";import { EyeInvisibleOutlined, EyeOutlined } from "@ant-design/icons";export const useColumns = (columns: AnyArray) => { const { useToken } = theme; const { token } = useToken(); const [checkedList, setCheckedList] = useState([]); const handleCheckedList = (item: string) => { const keys: string[] = []; if (checkedList.length > 0) { for (const value of checkedList) { keys.push(value); } } if (keys.indexOf(item) >= 0) { keys.splice(keys.indexOf(item), 1); } else { keys.push(item); } setCheckedList(keys as []); }; const newColumns = columns.map((item) => ({ ...item, hidden: item.dataIndex ? checkedList.includes(item.dataIndex as never) : false, })); const listColumns = () => { const optionColumns = columns.filter((item) => item.dataIndex); return ( <List style={{ height: 400, overflow: "scroll" }} size="small" className="checked-column" dataSource={optionColumns as []} renderItem={(item: Record<string, string>) => ( <List.Item onClick={() => handleCheckedList(item.dataIndex)}> <span>{item.title}</span> <span> {checkedList.includes(item.dataIndex as never) ? ( <EyeInvisibleOutlined style={{ color: token.colorFill }} rev={undefined} /> ) : ( <EyeOutlined style={{ color: token.colorInfo }} rev={undefined} /> )} </span> </List.Item> )} /> ); } return [newColumns, listColumns]}
2.页面index.tex
import { useColumns } from '../Component/newColumns'
const App: React.FC = () => {
const columns=[{
.....
}]
const [newColumns, listColumns] = useColumns(columns)//columns传入return (
<Table
columns={newColumns}//传入
pagination={{
showTotal: (total: number) => {
const totalPages = Math.ceil(total / pageSize);
return (
<>
<Popover content={listColumns} title="显示隐藏列" trigger="click">
<a style={{ paddingRight: '10px' }}>显示隐藏列</a >
</Popover>
共 {total} 条, 共 {totalPages} 页
</>
)
},
}}/>)}
export defalt App