gpt4 book ai didi

javascript - TreeView 中的 React.js 搜索过滤器

转载 作者:行者123 更新时间:2023-12-02 21:02:46 25 4
gpt4 key购买 nike

我正在 React.js 上进行一些初学者练习,并使用 Material-ui 创建了一个 TreeView 组件。现在我想实现一个搜索栏来在 TreeView 中搜索输入的关键字。这是我的示例数据:

[
{
id: 1,
name: "Item 1",
children: [
{
id: 2,
name: "Subitem 1",
children: [
{
id: 3,
name: "Misc 1",
children: [
{
id: 4,
name: "Misc 2"
}
]
}
]
},
{
id: 5,
name: "Subitem 2",
children: [
{
id: 6,
name: "Misc 3",
}
]
}
]
},
{
id: 7,
name: "Item 2",
children: [
{
id: 8,
name: "Subitem 1",
children: [
{
id: 9,
name: "Misc 1"
}
]
},
{
id: 10,
name: "Subitem 2",
children: [
{
id: 11,
name: "Misc 4"
},
{
id: 12,
name: "Misc 5"
},
{
id: 13,
name: "Misc 6",
children: [
{
id: 14,
name: "Misc 7"
}
]
}
]
}
]
}
]

渲染部分按预期工作。

const getTreeItemsFromData = treeItems => {
return treeItems.map(treeItemData => {
let children = undefined;
if (treeItemData.children && treeItemData.children.length > 0) {
children = getTreeItemsFromData(treeItemData.children);
}
return(
<TreeItem
key={treeItemData.id}
nodeId={treeItemData.id}
label={treeItemData.name}
children={children}/>
);
});
};

const DataTreeView = ({ treeItems }) => {
return(
<TreeView
defaultCollapseIcon={<ExpandMoreIcon />}
defaultExpandIcon={<ChevronRightIcon />}
>
{getTreeItemsFromData(treeItems)}
</TreeView>
);
};

class App extends Component {
render() {
return (
<div className="App">
<DataTreeView treeItems={searchedNodes} />
</div>
);
}
}

现在我正在努力实现搜索功能。我想使用 Material 搜索栏 ( https://openbase.io/js/material-ui-search-bar )

最佳答案

此解决方案假设您对树中的每个项目使用唯一的 id

它使用深度优先搜索算法。

在尝试之前,请修复您的示例数据的非唯一 ID。我一开始没有注意到它们,并浪费时间调试没有错误。

function dfs(node, term, foundIDS) {
// Implement your search functionality
let isMatching = node.name && node.name.indexOf(term) > -1;

if (Array.isArray(node.children)) {
node.children.forEach((child) => {
const hasMatchingChild = dfs(child, term, foundIDS);
isMatching = isMatching || hasMatchingChild;
});
}

// We will add any item if it matches our search term or if it has a children that matches our term
if (isMatching && node.id) {
foundIDS.push(node.id);
}

return isMatching;
}

function filter(data, matchedIDS) {
return data
.filter((item) => matchedIDS.indexOf(item.id) > -1)
.map((item) => ({
...item,
children: item.children ? filter(item.children, matchedIDS) : [],
}));
}

function search(term) {
// We wrap data in an object to match the node shape
const dataNode = {
children: data,
};

const matchedIDS = [];
// find all items IDs that matches our search (or their children does)
dfs(dataNode, term, matchedIDS);

// filter the original data so that only matching items (and their fathers if they have) are returned
return filter(data, matchedIDS);
}

关于javascript - TreeView 中的 React.js 搜索过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61302491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com