antd tree 搜索隐藏其他节点
时间: 2023-09-16 11:12:52 浏览: 127
您可以通过在 Antd Tree 的每个节点上添加一个 `visible` 属性,然后在搜索时设置符合条件的节点的 `visible` 属性为 `true`,不符合条件的节点的 `visible` 属性为 `false`,最后根据每个节点的 `visible` 属性来控制节点的显示和隐藏。具体实现可以参考以下代码:
```jsx
import { Tree } from 'antd';
import { useState } from 'react';
const { TreeNode } = Tree;
const generateTreeData = (count) => {
const treeData = [];
for (let i = 1; i <= count; i++) {
const node = {
title: `Node ${i}`,
key: i.toString(),
visible: true,
children: [],
};
for (let j = 1; j <= 3; j++) {
const childNode = {
title: `Node ${i}-${j}`,
key: `${i}-${j}`,
visible: true,
children: [],
};
for (let k = 1; k <= 3; k++) {
const grandchildNode = {
title: `Node ${i}-${j}-${k}`,
key: `${i}-${j}-${k}`,
visible: true,
children: [],
};
childNode.children.push(grandchildNode);
}
node.children.push(childNode);
}
treeData.push(node);
}
return treeData;
};
const TreeWithSearch = () => {
const [searchText, setSearchText] = useState('');
const [treeData, setTreeData] = useState(generateTreeData(5));
const handleSearch = (value) => {
setSearchText(value);
const filterTreeData = (data) => {
return data.map((node) => {
const lowerCaseTitle = node.title.toLowerCase();
const lowerCaseSearchText = value.toLowerCase();
if (lowerCaseTitle.includes(lowerCaseSearchText)) {
node.visible = true;
node.children = filterTreeData(node.children);
} else {
node.visible = false;
node.children = filterTreeData(node.children);
}
return node;
});
};
setTreeData(filterTreeData(treeData));
};
const renderTreeNodes = (data) => {
return data.map((node) => {
if (!node.visible) {
return null;
}
if (node.children && node.children.length > 0) {
return (
<TreeNode key={node.key} title={node.title}>
{renderTreeNodes(node.children)}
</TreeNode>
);
}
return <TreeNode key={node.key} title={node.title} />;
});
};
return (
<div>
<input value={searchText} onChange={(e) => handleSearch(e.target.value)} placeholder="Search" />
<Tree>{renderTreeNodes(treeData)}</Tree>
</div>
);
};
```
在这个实现中,我们在每个节点上添加了一个 `visible` 属性,初始值都为 `true`。在搜索时,我们根据搜索文本来判断每个节点是否符合条件,然后设置其 `visible` 属性为相应的值。最后在渲染树节点时,我们根据每个节点的 `visible` 属性来决定是否显示该节点。
阅读全文