antd@5
<TableBasic columns={[]} dataSource={[]} />
import React, { useMemo, useState, useEffect } from 'react';
import { Button, Checkbox, Dropdown, Table, Card } from 'antd';
import { UnorderedListOutlined } from '@ant-design/icons';
/**
* 表格展示列
* @param props initShowCols: 初始指定展示哪些列,默认展示全部
* @param props 其他props参考antd@5官方文档
* @returns React.ReactNode
*/
function TableBasic(props) {
const { columns = [], initShowCols, ...others } = props ?? {};
const [state, setState] = useState({
checkedCols: (initShowCols || columns)?.map((item) => item.dataIndex),
open: false,
});
const { checkedCols, open } = state;
useEffect(() => {
const clickHandle = (e) => {
const dropdownWrap = document.querySelector('.__ant_dropdown__');
const btn: any = dropdownWrap?.querySelector('.ant-btn');
const dropdown: any = document.querySelector('.ant-dropdown');
if (!btn.contains(e.target) && !dropdown?.contains(e.target)) {
setState((pre) => ({ ...pre, open: false }));
}
};
window.addEventListener('click', clickHandle);
return () => {
window.removeEventListener('click', clickHandle);
};
}, []);
const checkedChange = (e) => {
const { value, checked } = e.target;
if (checked) {
setState((pre) => ({
...pre,
checkedCols: [...pre.checkedCols, value],
}));
} else {
setState((pre) => ({
...pre,
checkedCols: pre.checkedCols.filter((v) => v !== value),
}));
}
};
const items = useMemo(
() =>
columns?.map((item) => {
return {
key: item.dataIndex,
label: (
<div>
<Checkbox
style={{ width: '100%' }}
onChange={checkedChange}
value={item.dataIndex}
checked={checkedCols?.includes(item.dataIndex)}
>
{item.title}
</Checkbox>
</div>
),
};
}),
[columns, checkedCols],
);
const filterCols = useMemo(() => {
return columns?.filter((item) => checkedCols?.includes(item?.dataIndex));
}, [checkedCols]);
return (
<div style={{ marginBottom: 12 }}>
<Card>
<div style={{ textAlign: 'right', marginBottom: 12 }} className="__ant_dropdown__">
<Dropdown menu={{ items }} open={open}>
<Button
type="default"
icon={<UnorderedListOutlined />}
onClick={(e) => {
e.preventDefault();
setState({ ...state, open: !open });
}}
>
设置表格展示列
</Button>
</Dropdown>
</div>
<Table columns={filterCols} {...others} />
<Card>
</div>
);
}
export default TableBasic;