ant design提供的可搜索树的案例(此案例不要被里面的x,y,z所迷惑,仔细看看,他们只是造假数据的),以及异步数据加载树的案例,下面对这两个案例合二为一留作参考
import React from 'react';
import {Tree, Input} from 'antd';
const TreeNode = Tree.TreeNode;
const Search = Input.Search;
const getParentKey = (title, tree) => {
let parentKey;
for (let i = 0; i < tree.length; i++) {
const node = tree[i];
if (node.children) {
if (node.children.some(item => item.title === title)) {
parentKey = node.key;
} else if (getParentKey(title, node.children)) {
parentKey = getParentKey(title, node.children);
}
}
}
return parentKey;
};
const dataList = [];
const generateList = (data) => {
for (let i = 0; i < data.length; i++) {
const node = data[i];
const key = node.key;
dataList.push({key, title: node.title});
if (node.children) {
generateList(node.children);
}
}
};
/*对于异步加载的子节点使用该key进行自增赋值*/
let key = 10;
class SearchTree extends React.Component {
state = {
expandedKeys: ['1'],
searchValue: '',
autoExpandParent: true,
gData: [
{
title: 'parent1',
key: '1',
children: [
{
title: 'parent2',
key: '2',
children: [
{
title: 'leaf1',
key: '3',
},
{
title: 'leaf2',
key: '4',
},
{
title: 'leaf3',
key: '5',
}
]
},
{
title: 'parent3',
key: '6',
children: [
{
title: 'leaf4',
key: '7',
},
{
title: 'leaf5',
key: '8',
},
{
title: 'leaf6',
key: '9',
}
]
},
]
}
]
};
onSelect = (selectedKeys, info) => {
/*用于打开该节点的详细信息*/
console.log('selected', selectedKeys, info);
console.log(this.state.expandedKeys);
};
onExpand = (expandedKeys) => {
this.setState({
expandedKeys,
autoExpandParent: false,
});
};
onChange = (e) => {
const value = e.target.value;
const expandedKeys = dataList.map((item) => {
if (item.title.indexOf(value) > -1) {
return getParentKey(item.title, this.state.gData);
}
return null;
}).filter((item, i, self) => item && self.indexOf(item) === i);
this.setState({
expandedKeys,
searchValue: value,
autoExpandParent: true,
});
};
loop = data => data.map((item) => {
let {searchValue} = this.state;
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 ? (
{beforeStr}
'#f50'}}>{searchValue}
{afterStr}
) : {item.title};
if (item.children) {
return (
{this.loop(item.children)}
);
}
return ;
}) ;
onLoadData = (treeNode) => {
return new Promise((resolve) => {
if (treeNode.props.children) {
resolve();
return;
}
setTimeout(() => {
treeNode.props.dataRef.children = [
{ title: 'Child', key: (++key + '') },
{ title: 'Child', key: (++key + '') },
];
this.setState({
gData: [...this.state.gData],
});
resolve();
}, 1000);
});
};
render() {
const {expandedKeys, autoExpandParent, gData} = this.state;
// 进行数组扁平化处理
generateList(gData);
return (
'200px'}}>
8}} placeholder="Search" onChange={this.onChange}/>
this.onSelect}
onExpand={this.onExpand}
expandedKeys={expandedKeys}
autoExpandParent={autoExpandParent}
loadData={this.onLoadData}
>
{this.loop(gData)}
);
}
}
export default SearchTree;