在 Ant Design 中,Table 组件的 getColumnSearchProps 方法用于实现表格列的搜索功能。然而,当涉及到嵌套对象时,该方法可能无法正常工作。以下是解决该问题的代码示例:
import React, { useState } from 'react';
import { Table, Input, Button } from 'antd';
const data = [
{
id: 1,
name: 'John Doe',
details: {
age: 25,
address: '123 Street'
}
},
{
id: 2,
name: 'Jane Smith',
details: {
age: 30,
address: '456 Avenue'
}
},
// ...
];
const App = () => {
const [searchText, setSearchText] = useState('');
const [searchedColumn, setSearchedColumn] = useState('');
const getColumnSearchProps = dataIndex => ({
filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
setSelectedKeys(e.target.value ? [e.target.value] : [])}
onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
style={{ width: 188, marginBottom: 8, display: 'block' }}
/>
),
filterIcon: filtered => ,
onFilter: (value, record) => {
const nestedValue = record[dataIndex];
if (typeof nestedValue === 'object') {
// 嵌套对象
return nestedValue && nestedValue.filter(val => val.includes(value)).length > 0;
} else {
// 非嵌套对象
return nestedValue ? nestedValue.toString().toLowerCase().includes(value.toLowerCase()) : false;
}
},
});
const handleSearch = (selectedKeys, confirm, dataIndex) => {
confirm();
setSearchText(selectedKeys[0]);
setSearchedColumn(dataIndex);
};
const handleReset = clearFilters => {
clearFilters();
setSearchText('');
};
const columns = [
{
title: 'ID',
dataIndex: 'id',
key: 'id',
...getColumnSearchProps('id'),
},
{
title: 'Name',
dataIndex: 'name',
key: 'name',
...getColumnSearchProps('name'),
},
{
title: 'Age',
dataIndex: ['details', 'age'], // 使用数组指定嵌套对象路径
key: 'age',
...getColumnSearchProps(['details', 'age']),
},
{
title: 'Address',
dataIndex: ['details', 'address'],
key: 'address',
...getColumnSearchProps(['details', 'address']),
},
// ...
];
return
;
};
export default App;
在上面的代码中,我们通过 dataIndex
参数传递了嵌套对象的路径,然后在 onFilter
方法中处理嵌套对象的搜索逻辑。这样,就可以在嵌套对象中实现正常的搜索功能。