antd的table自定义筛选
时间: 2023-10-07 14:11:03 浏览: 75
如果 Antd 的 Table 组件提供的筛选功能不能满足我们的需求,我们可以通过自定义筛选实现更加灵活的功能。具体步骤如下:
1. 在 `columns` 中设置需要筛选的列的 `filterDropdown` 和 `onFilterDropdownVisibleChange` 属性,如下所示:
```javascript
const columns = [
{
title: '姓名',
dataIndex: 'name',
key: 'name',
filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
<div style={{ padding: 8 }}>
<Input
placeholder="请输入姓名"
value={selectedKeys[0]}
onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
onPressEnter={() => confirm()}
/>
<Button type="primary" onClick={() => confirm()} style={{ margin: '0 8px' }}>
筛选
</Button>
<Button onClick={() => clearFilters()}>重置</Button>
</div>
),
onFilterDropdownVisibleChange: visible => {
if (visible) {
setTimeout(() => this.searchInput.select());
}
},
onFilter: (value, record) => record.name.indexOf(value) === 0,
},
{
title: '年龄',
dataIndex: 'age',
key: 'age',
},
{
title: '地址',
dataIndex: 'address',
key: 'address',
},
];
```
在上述代码中,我们通过 `filterDropdown` 属性自定义了筛选面板的内容,包括一个输入框、一个筛选按钮和一个重置按钮。在输入框中输入筛选条件,然后点击筛选按钮即可进行筛选。`onFilterDropdownVisibleChange` 属性用于在筛选面板显示时自动聚焦输入框。
2. 在 `Table` 组件中设置 `columns` 和 `dataSource` 属性,如下所示:
```javascript
class App extends React.Component {
state = {
dataSource: [],
};
componentDidMount() {
// 模拟数据请求
setTimeout(() => {
this.setState({
dataSource: [
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
},
{
key: '3',
name: 'Joe Black',
age: 32,
address: 'Sidney No. 1 Lake Park',
},
{
key: '4',
name: 'Jim Red',
age: 32,
address: 'London No. 2 Lake Park',
},
],
});
}, 1000);
}
render() {
const { dataSource } = this.state;
return <Table columns={columns} dataSource={dataSource} />;
}
}
```
在上述代码中,我们只设置了 `columns` 和 `dataSource` 属性,没有处理筛选操作,因为筛选操作已经在 `filterDropdown` 中实现了。
注意:自定义筛选的实现方式比较灵活,可以根据具体需求进行适当的调整。