import React, { useEffect, useState, useMemo } from 'react';
import { Input, Tree } from 'antd';
const { Search } = Input;
let treeList = [
{
title: 'Node 1',
key: '0-0',
children: [
{
title: 'Child Node 1-1',
key: '0-0-0',
children: [
{
title: 'Grandchild Node 1-1-1',
key: '0-0-0-0',
},
{
title: 'Grandchild Node 1-1-2',
key: '0-0-0-1',
},
],
},
{
title: 'Child Node 1-2',
key: '0-0-1',
},
],
},
{
title: 'Node 2',
key: '0-1',
children: [
{
title: 'Child Node 2-1',
key: '0-1-0',
},
],
},
{
title: 'Node 3',
key: '0-2',
},
];
const TreeBox = () => {
const [expandedKeys, setExpandedKeys] = useState([]);
const [searchValue, setSearchValue] = useState('');
const [autoExpandParent, setAutoExpandParent] = useState(true);
const [treeData, setTreeData] = useState([]);
useEffect(() => {
// 初始化数据
setTreeData(treeList);
}, []);
const onExpand = (newExpandedKeys) => {
setExpandedKeys(newExpandedKeys);
setAutoExpandParent(false);
};
const onChange = (e) => {
const { value } = e.target;
const newExpandedKeys = treeData
.flatMap((item) => {
if (item.title.includes(value)) {
return [item.key];
}
return item.children
? item.children.flatMap((child) => {
if (child.title.includes(value)) {
return [child.key];
}
return [];
})
: [];
})
.filter((item, i, self) => !!(item && self.indexOf(item) === i));
setExpandedKeys(newExpandedKeys);
setSearchValue(value);
setAutoExpandParent(true);
};
const treeDataFiltered = useMemo(() => {
const loop = (data) =>
data.map((item) => {
const strTitle = item.title;
const index = strTitle.indexOf(searchValue);
const beforeStr = strTitle.substring(0, index);
const afterStr = strTitle.slice(index + searchValue.length);
const title =
index > -1 ? (
<span key={item.key}>
{beforeStr}
<span className="site-tree-search-value">{searchValue}</span>
{afterStr}
</span>
) : (
<span key={item.key}>{strTitle}</span>
);
if (item.children) {
return {
title,
key: item.key,
children: loop(item.children),
};
}
return {
title,
key: item.key,
};
});
return loop(treeData);
}, [searchValue, treeData]);
return (
<div>
<Search
style={{
marginBottom: 8,
}}
placeholder="Search"
onChange={onChange}
/>
<Tree
onExpand={onExpand}
expandedKeys={expandedKeys}
autoExpandParent={autoExpandParent}
treeData={treeDataFiltered}
/>
</div>
);
};
export default TreeBox;