在Ant Design for React中,可以使用Table组件来显示和隐藏特定列。下面是一个示例代码,演示如何根据用户的选择来显示或隐藏特定列:
import React, { useState } from 'react';
import { Table } from 'antd';
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
width: 150,
},
{
title: 'Age',
dataIndex: 'age',
key: 'age',
width: 150,
},
{
title: 'Address',
dataIndex: 'address',
key: 'address',
width: 200,
},
];
const data = [
{
key: '1',
name: 'John',
age: 25,
address: 'New York',
},
{
key: '2',
name: 'Mike',
age: 30,
address: 'Los Angeles',
},
{
key: '3',
name: 'Lisa',
age: 35,
address: 'Chicago',
},
];
const App = () => {
const [showName, setShowName] = useState(true);
const [showAge, setShowAge] = useState(true);
const [showAddress, setShowAddress] = useState(true);
const handleToggleColumn = (columnKey, show) => {
switch (columnKey) {
case 'name':
setShowName(show);
break;
case 'age':
setShowAge(show);
break;
case 'address':
setShowAddress(show);
break;
default:
break;
}
};
const columnsWithToggle = columns.map((column) => {
const { key, ...restColumnProps } = column;
return {
...restColumnProps,
key,
render: (text, record) => showColumnByKey(key) ? text : null,
};
});
const showColumnByKey = (key) => {
switch (key) {
case 'name':
return showName;
case 'age':
return showAge;
case 'address':
return showAddress;
default:
return true;
}
};
return (
);
};
export default App;
在这个示例中,我们使用useState来跟踪每个列的显示状态。handleToggleColumn函数负责更新相应列的显示状态。showColumnByKey函数根据列的键返回相应的显示状态。
在render函数中,我们使用showColumnByKey函数来确定每个单元格是否应该显示。如果显示状态为false,我们返回null以隐藏列。
最后,我们在Table组件中使用columnsWithToggle作为列配置,在数据源中使用data作为表格的数据。使用复选框来切换每个列的显示/隐藏状态。