技术栈:Ant Design Pro
原理:将列设为状态管理
代码:
1.全部列
const columnsArr = [
{
title: '时效缺陷',
dataIndex: 'ProblemFlag',
},
{
title: '病案号',
dataIndex: 'MedicareN',
},
...
]
2.状态管理
const [columns, setColumns] = useState<any>([...columnsArr]);
3.表格渲染
<Table
rowKey="ID"
size="small"
bordered
dataSource={tableList}
columns={columns}
...
/>
4.列配置选择框渲染
{/* 表格列配置 */}
<div style={{ margin: '2px 10px', textAlign: 'left' }}>
<span style={{ marginRight: 10 }}>列配置</span>
<Select
showSearch
allowClear
placeholder="[列配置]"
mode="multiple"
style={{ minWidth: 150 }}
onChange={onColumnChange}
>
{optionsCreate(columnsArr)}
</Select>
</div>
5.列配置函数
//列配置思路
//1.进行选择,选择内容为需要展示的列
//2.选择完成后,关联事件,重新渲染表格
//选中了哪些列
const onColumnChange = (value: any) => {
//value即为选中项组成的数组
const arr = [];
for (let i = 0; i < value.length; i++) {
for (let j = 0; j < columnsArr.length; j++) {
if (value[i] == columnsArr[j].dataIndex) {
arr.push(columnsArr[j]);
}
}
}
setColumns(arr);
};
6.其他
选择项生成函数
//生成列配置项
const optionsCreate = (arr: any) => {
const options: any = [];
if (!arr) {
return;
}
for (let i = 0; i < arr.length; i++) {
options.push(
<Option key={arr[i].dataIndex} value={arr[i].dataIndex}>
{arr[i].title}
</Option>,
);
}
return options;
};
const { Option } = Select;
7.效果