在 Ant Design 的 Table 组件中,可以通过 filterDropdown 属性来自定义筛选框。以下是一个封装自定义筛选框的示例,支持输入筛选和多选筛选功能:
1. 封装自定义筛选框
我们可以定义一个函数 getCustomFilterDropdown,根据传入的参数动态生成筛选框组件。
import React from "react";
import { Input, Button, Checkbox, Space } from "antd";
// 自定义筛选框函数
const getCustomFilterDropdown = (type, placeholder, onSearch) => ({
setSelectedKeys,
selectedKeys,
confirm,
clearFilters,
}) => {
const handleSearch = () => {
onSearch(selectedKeys);
confirm();
};
const handleReset = () => {
setSelectedKeys([]);
onSearch([]);
clearFilters?.();
};
if (type === "input") {
return (
<div style={{ padding: 8 }}>
<Input
placeholder={placeholder}
value={selectedKeys[0]}
onChange={(e) =>
setSelectedKeys(e.target.value ? [e.target.value] : [])
}
onPressEnter={handleSearch}
style={{ width: "100%", marginBottom: 8 }}
/>
<Space>
<Button type="primary" onClick={handleSearch} size="small">
搜索
</Button>
<Button onClick={handleReset} size="small">
重置
</Button>
</Space>
</div>
);
}
if (type === "checkbox") {
return (
<div style={{ padding: 8 }}>
<Checkbox.Group
value={selectedKeys}
onChange={(values) => setSelectedKeys(values)}
>
{placeholder.map((option) => (
<Checkbox value={option.value} key={option.value}>
{option.text}
</Checkbox>
))}
</Checkbox.Group>
<Space style={{ marginTop: 8 }}>
<Button type="primary" onClick={handleSearch} size="small">
确认
</Button>
<Button onClick={handleReset} size="small">
重置
</Button>
</Space>
</div>
);
}
return null;
};
2. 使用自定义筛选框
在定义 Table 的 columns 时,将 filterDropdown 设置为封装好的函数返回值。
const columns = [
{
title: "姓名",
dataIndex: "name",
filterDropdown: getCustomFilterDropdown("input", "请输入姓名搜索", (keys) => {
console.log("筛选结果:", keys);
}),
},
{
title: "城市",
dataIndex: "city",
filterDropdown: getCustomFilterDropdown("checkbox", [
{ text: "北京", value: "北京" },
{ text: "上海", value: "上海" },
{ text: "广州", value: "广州" },
], (keys) => {
console.log("筛选结果:", keys);
}),
},
];
3. 注意事项
- 后端筛选:如果需要将筛选条件传递到后端进行筛选,可以在
onSearch回调中处理筛选逻辑,例如将筛选条件存储到状态中,并通过Table的onChange触发请求。 - 样式调整:可以根据需求调整
filterDropdown的样式,使其更符合页面设计。
通过这种方式,你可以灵活地为 Ant Design 的 Table 组件添加自定义筛选框,满足不同的业务需求。