antd的treedata组件如何使用filtertreenode属性根据label值搜索
时间: 2024-03-08 17:49:15 浏览: 85
antd的treedata组件也可以通过使用`filterTreeNode`属性根据`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}
filterTreeNode={(node) => {
const { title } = node;
return title.indexOf(searchValue) > -1;
}}
treeData={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`中包含输入值的节点,并将它们的父节点展开。我们使用了`filterTreeNode`属性来定义一个过滤函数,这个过滤函数会根据节点的`title`属性和输入值进行匹配。最后,我们将更新后的`treeData`通过`loop()`函数渲染到`Tree`组件中。
阅读全文