antd的treedata组件如何根据label值搜索
时间: 2024-03-08 12:49:12 浏览: 114
antd Tree组件 搜索标红 例子
5星 · 资源好评率100%
antd的treedata组件可以通过使用treeData.filter()方法根据label值进行搜索。可以使用以下代码实现:
```
const { Search } = Input;
function TreeSearch() {
const [expandedKeys, setExpandedKeys] = useState([]);
const [searchValue, setSearchValue] = useState('');
const [autoExpandParent, setAutoExpandParent] = useState(true);
const [treeData, setTreeData] = useState([
{
title: 'Node1',
key: '0-0',
children: [
{
title: 'Child Node1',
key: '0-0-0',
},
{
title: 'Child Node2',
key: '0-0-1',
},
],
},
{
title: 'Node2',
key: '0-1',
children: [
{
title: 'Child Node3',
key: '0-1-0',
},
{
title: 'Child Node4',
key: '0-1-1',
},
],
},
]);
const onExpand = (expandedKeys) => {
setExpandedKeys(expandedKeys);
setAutoExpandParent(false);
};
const onChange = (e) => {
const { value } = e.target;
const expandedKeys = treeData
.map((item) => {
if (item.title.indexOf(value) > -1) {
return getParentKey(item.key, treeData);
}
return null;
})
.filter((item, i, self) => item && self.indexOf(item) === i);
setSearchValue(value);
setExpandedKeys(expandedKeys);
setAutoExpandParent(true);
};
const loop = (data) =>
data.map((item) => {
const index = item.title.indexOf(searchValue);
const beforeStr = item.title.substr(0, index);
const afterStr = item.title.substr(index + searchValue.length);
const title =
index > -1 ? (
<span>
{beforeStr}
<span style={{ color: '#f50' }}>{searchValue}</span>
{afterStr}
</span>
) : (
<span>{item.title}</span>
);
if (item.children) {
return { title, key: item.key, children: loop(item.children) };
}
return {
title,
key: item.key,
};
});
return (
<div>
<Search style={{ marginBottom: 8 }} placeholder="Search" onChange={onChange} />
<Tree
onExpand={onExpand}
expandedKeys={expandedKeys}
autoExpandParent={autoExpandParent}
treeData={loop(treeData)}
/>
</div>
);
}
function getParentKey(key, tree) {
let parentKey;
for (let i = 0; i < tree.length; i++) {
const node = tree[i];
if (node.children) {
if (node.children.some((item) => item.key === key)) {
parentKey = node.key;
} else if (getParentKey(key, node.children)) {
parentKey = getParentKey(key, node.children);
}
}
}
return parentKey;
}
```
这个代码中,我们使用了antd的Tree组件和Input组件。当用户在输入框中输入时,我们会搜索treeData中所有title中包含输入值的节点,并将它们的父节点展开。我们使用了递归的方式遍历treeData并更新所有匹配的节点。最后,我们将更新后的treeData通过loop()函数渲染到Tree组件中。
阅读全文