3、ant-design table 可选列的实现
import React, { Component } from 'react';
import { Table, Checkbox } from 'antd';
const CheckboxGroup = Checkbox.Group;
//列表数据
const data = [{
key: '1',
name: 'John Brown',
gender: '男',
age: 32,
address: 'New York No. 1 Lake Park',
}, {
key: '2',
name: 'Joe Black',
gender: '男',
age: 42,
address: 'London No. 1 Lake Park',
}, {
key: '3',
name: 'Jim Green',
gender: '女',
age: 32,
address: 'Sidney No. 1 Lake Park',
}, {
key: '4',
name: 'Jim Red',
gender: '女',
age: 32,
address: 'London No. 2 Lake Park',
}];
// 可选列(CheckboxGroup)
const columnOptions = [
{ label: 'Gender', value: 'Gender' },
{ label: 'Age', value: 'Age' },
{ label: 'Address', value: 'Address' }
];
// 自定义列(Table)
const defcolumns = [{
title: 'Gender',
dataIndex: 'gender',
key: 'gender',
}, {
title: 'Age',
dataIndex: 'age',
key: 'age',
}, {
title: 'Address',
dataIndex: 'address',
key: 'address',
}];
let columnOptions_default = []; // 默认选中的checkbox
for(let i in columnOptions) {
columnOptions_default.push(columnOptions[i].value);
}
class Demo extends Component {
constructor(props) {
super(props);
this.state = {
columns: []
};
this.onChange = this.onChange.bind(this);
}
componentDidMount() {
let columns = [{
title: 'Name',
dataIndex: 'name',
key: 'name',
filterDropdown: () => (
<div className="custom-filter-dropdown">
<CheckboxGroup options={columnOptions} defaultValue={columnOptions_default} onChange={this.onChange} />
</div>
),
}];
columns = columns.concat(defcolumns); // 初始化显示所有列
this.setState({
columns: columns
});
}
render() {
const {columns} = this.state;
return <Table columns={columns} dataSource={data} />;
}
onChange(checkedValues) {
let data = [{
title: 'Name',
dataIndex: 'name',
key: 'name',
filterDropdown: () => (
<div className="custom-filter-dropdown">
<CheckboxGroup options={columnOptions} defaultValue={columnOptions_default} onChange={this.onChange} />
</div>
),
}];
defcolumns.forEach((r)=>{
checkedValues.forEach(rs=>{
if(r.title == rs) {
data.push(r);
}
});
});
console.log(data);
this.setState({ columns: data });
}
}
export default Demo;
更多angular1/2/4/5、ionic1/2/3、react、vue、微信小程序、nodejs等技术文章、视频教程和开源项目,请关注微信公众号——全栈弄潮儿。
微信公众号.png
网友评论