当使用Antd Tree进行搜索时,可能会遇到搜索结果未展开子列表子项的问题。解决方法是在onSearch事件触发时,手动展开包含匹配值的子列表。
代码示例:
import React, { useState } from 'react';
import { Tree } from 'antd';
const { TreeNode } = Tree;
const treeData = [
{
title: 'parent 1',
key: '0-0',
children: [
{
title: 'child 1',
key: '0-0-0',
children:[
{
title: 'grand child 1',
key: '0-0-0-0',
}
]
},
{
title: 'child 2',
key: '0-0-1',
},
],
},
{
title: 'parent 2',
key: '0-1',
children: [
{
title: 'child 3',
key: '0-1-0',
},
{
title: 'child 4',
key: '0-1-1',
children:[
{
title: 'grand child 2',
key: '0-1-1-0',
}
]
},
],
},
];
const SearchableTree = ({treeData}) => {
const [expandedKeys, setExpandedKeys] = useState([]);
const onSearch = (value) => {
if (value) {
const expandedKeys = treeData
.map((item) => {
if (item.title.includes(value)) {
return getParentKey(item.key, treeData);
}
return null;
})
.filter((item, i, self) => item && self.indexOf(item) === i);
setExpandedKeys(expandedKeys);
} else {
setExpandedKeys([]);
}
};
const getParentKey = (key, tree) => {
let parentKey;
for (const node of tree) {
if (node.children) {
if (node.children.some((item) => item.key === key)) {
parentKey = node.key;
} else if
上一篇:AntdTreeSelect发出警告:树中存在相同的`value`:undefined
下一篇:AntdTree组件在使用时遇到了一个问题,即从后台获取数据时,当选择父节点时,所有子节点也会被全选,如何修改才能正常显示?请给出技术性的解答。