需求
現在有一個在table里面做篩選的需求,在antd的table文檔里很容易找到相關API,在官方的例子中是用filters定義菜單數據,用onFilter監控變化。
官方例子:
{
title: 'Address',
dataIndex: 'address',
filters: [
{
text: 'London',
value: 'London',
},
{
text: 'New York',
value: 'New York',
},
],
onFilter: (value, record) => record.address.indexOf(value) === 0,
},
我們的項目前端做了分頁,在前端做篩選是不合適的,數據集不完整;所以篩選是在后端做的,我們需要的是讓請求帶上篩選字段傳過去。
onFilter/onChange
剛開始我想當然在onFilter里做,因為onFIlter可以拿到當前篩選的value,但是在控制台發現在篩選操作時發出了很多條相同的請求。
看了下onFilter的源碼:
可以看到onFilter是對data里的每一個record,也就是每條列表數據執行一次onFilter方法,如果把后端交互寫在onFilter中,就會執行多次。所以不能使用onFilter。
這時候我想使用的是Table的onChange,這個函數有三個入參,pagination、filter和sort,也就是可以監聽table的頁碼、篩選和排序信息,但是由於我們項目的pagination是自定義的類,如果用onChange,要多做一些antd內置pagination和自定義pagination類的判斷,不然就會有冗余請求。
filterDropdown
最后選擇使用filterDropdown這個屬性,也就是自定義篩選菜單,交互也是自己寫,自由度很高。為了可復用性高,將其封裝為一個函數。
該函數僅需傳入篩選操作發生時要執行的函數,其他參數從antd給的props里取。由此依然可以用antd的filters等api。返回一個完整的菜單組件。
// 封裝的filterDropdown函數,
export const getColumnCheckboxGroupFilterDropdown = (onSearch: (value: string[]) => void) => (
props: FilterDropdownProps
) => {
const { setSelectedKeys, selectedKeys, filters, confirm, clearFilters } = props;
const onChange = (checkedValues: string[]) => {
setSelectedKeys(checkedValues);
};
const clear = () => {
setSelectedKeys([]);
onSearch([]);
clearFilters();
};
const onOk = () => {
onSearch(selectedKeys as string[]);
confirm();
};
return (
<div className="filter-content">
<Checkbox.Group onChange={onChange} value={selectedKeys}>
{filters?.map((item) => (
<Checkbox value={item.value} key={item.value as string}>
{item.text}
</Checkbox>
))}
</Checkbox.Group>
<Divider />
<div className="footer">
<Button type="link" disabled={!selectedKeys?.length} onClick={clear}>
Reset
</Button>
<Button type="primary" onClick={onOk}>
OK
</Button>
</div>
</div>
);
};
// 在定義table column時使用
{
dataIndex: 'sth',
title: 'title',
filters: [
{
text: 'filter1',
value: 'filter1',
},
{
text: 'filter2',
value: 'filter2',
},
],
filterDropdown: getColumnCheckboxGroupFilterDropdown(
// onSearch func like setData
),
};