import React, { Key, useState } from 'react';
import { Table, Input } from 'antd';
const { Search } = Input;
const dataSource = [
{
key: '1',
name: 'Parent 1',
children: [
{
key: '1-1',
name: 'Child 1-1',
},
{
key: '1-2',
name: 'Child 1-2',
},
],
},
{
key: '2',
name: 'Parent 2',
children: [
{
key: '2-1',
name: 'Child 2-1',
},
],
},
];
const TreeTable = () => {
const [searchText, setSearchText] = useState('');
const [expandedKeys, setExpandedKeys] = useState<Key[]>([]);
const handleSearch = (value: string) => {
setSearchText(value);
const keys: Key[] = [];
dataSource.forEach((item) => {
if (item.name.toLowerCase().includes(value.toLowerCase())) {
keys.push(item.key); // 如果父节点匹配,将父节点key添加到展开的keys中
} else if (item.children) {
item.children.forEach((child) => {
if (child.name.toLowerCase().includes(value.toLowerCase())) {
keys.push(item.key); // 如果子节点匹配,将父节点key添加到展开的keys中
}
});
}
});
setExpandedKeys(keys);
};
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
render: (text: string) => {
const index = text.toLowerCase().indexOf(searchText.toLowerCase());
const beforeStr = text.substring(0, index);
const afterStr = text.substring(index + searchText.length);
const highlightedText =
index > -1 ? (
<>
{beforeStr}
<span style={{ backgroundColor: '#ffc069' }}>{searchText}</span>
{afterStr}
</>
) : (
text
);
return <span>{highlightedText}</span>;
},
},
];
return (
<div>
<Search placeholder="Search" onSearch={(e) => handleSearch(e)} />
<Table
dataSource={dataSource}
columns={columns}
expandable={{
expandedRowKeys: expandedKeys,
onExpandedRowsChange: (keys) => setExpandedKeys(keys as Key[]),
}}
/>
</div>
);
};
export default TreeTable;
antd table 树形数据展示 搜索子数据 展开父节点并高亮搜索出来的数据
于 2024-02-07 10:58:56 首次发布