我有一个使用对象数组递归绘制的树。我能够通过所有展开和折叠相关的功能显示树形结构。现在,我想使用一个输入元素在整个树中进行搜索。这个搜索应该是递归的。当叶节点匹配时,树应该显示到那个叶节点的所有节点,并被展开。当匹配到一个中间或根节点时,它应该只显示到那个级别,并带有可折叠图标,然后可以展开。
这是我目前尝试过的。
节点组件
import React, { useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
export const Node = ({ node, level, currentActive, setCurrentActive }) => {
const [isOpen, setIsOpen] = useState(false);
const hasChildren = !!node?.categories?.length;
const categoryType =
level === 0 ? "category" : !hasChildren ? "leaf" : "group";
if (!node) return null;
const { name, key, categories } = node;
const activeClassName = currentActive === name ? "active" : "";
return (
<>
<div
className={`list-row level-${level} ${categoryType} ${activeClassName}`}
onClick={() => {
setIsOpen((open) => !open);
if (!hasChildren) {
setCurrentActive((prevName) => (!(prevName === name) ? name : ""));
}
}}
key={key}
>
<div className="list-item-holder">
{hasChildren && (
<div className="list-item-expander-holder">
<span
className={`expand-collapse-icon ${
isOpen ? "collapse" : "expand"
}`}
>
<span className="expand-icon">
<FontAwesomeIcon icon="caret-down" />
</span>
<span className="collapse-icon">
<FontAwesomeIcon icon="caret-right" />
</span>
</span>
</div>
)}
<div className="list-item-details-holder">{name}</div>
</div>
</div>
{isOpen && hasChildren && (
<div className="list-row-children">
{categories.map((node) => (
<Node
key={node.key}
node={node}
level={level + 1}
currentActive={currentActive}
setCurrentActive={setCurrentActive}
/>
))}
</div>
)}
</>
);
};
到目前为止,我尝试过的搜索功能都没有起作用。
function searchTree(tree, query) {
function traverse(node, query) {
if (node.categories) {
traverse(node.categories, query);
}
return {
...node,
categories: node?.categories?.filter(({ name }) => name === query)
};
}
return tree.map((root) => traverse(root, query));
}
有人能帮忙实现这个吗?我只是一个初学者,正在尝试学习。非常感谢您的帮助。
沙盒链接:https://codesandbox.io/s/tree-updated-with-search-forked-ms2b6w?file=/src/DrawnTree.jsx:223-617