在React 框架里使用ant design确买,ant design tree 組件網(wǎng)址:https://ant-design.gitee.io/components/tree-cn/
//導入antd;
import { Tree } from 'antd';
const { DirectoryTree } = Tree;
//創(chuàng)建組件
class Search extends React.Component{
constructor(props) {
super(props);
this.state = {
select_treenodes:[ ],
expandFlag:[ ],
tree_data:[ ],
}
}
onSelect = (selectedKeys, info) => {
//點擊樹節(jié)點觸發(fā)事件可以打印selectedKeys殷勘,info查看它的值
}
// 展開/收起節(jié)點時觸發(fā)(把指定張開的父節(jié)點重新賦值;如果加了 expandedKeys,就必須用這一步按咒,不然不能展開節(jié)點以及收起節(jié)點)
onExpand=(expandedKeys, {expanded: bool, node})=>{
console.log(expandedKeys);
this.setState({
expandFlag:expandedKeys,
}
}
//當搜索框輸入時觸發(fā)
SearchChange = (e)=>{
console.log(e.target.value) //輸入的值打印
let data = this.state.tree_data; //節(jié)點數(shù)據(jù)挖帘;
//遍歷節(jié)點數(shù)據(jù)
for(let i =0; i <data[0].children.length; i++){
if(data[0].children[i].title == e.target.value){ //如果輸入的值等于節(jié)點的title,把節(jié)點張開捺僻,標記節(jié)點乡洼;
console.log(data[0].children[i].key) //打印key崇裁,如果key是number類型則要轉化成String類型;
this.setState({
select_treenodes:[data[0].children[i].key], //設置選中的樹節(jié)點
expandFlag:[String(data[0].key)], //展開指定父節(jié)點
})
}
}
console.log(this.state.tree_data)
}
//渲染
render(){
//tree數(shù)據(jù)
const treeData = [
{
title: 'parent 0',
key: '0-0',
children: [
{ title: 'leaf 0-0', key: '0-0-0', isLeaf: true },
{ title: 'leaf 0-1', key: '0-0-1', isLeaf: true },
],
},
{
title: 'parent 1',
key: '0-1',
children: [
{ title: 'leaf 1-0', key: '0-1-0', isLeaf: true },
{ title: 'leaf 1-1', key: '0-1-1', isLeaf: true },
],
},
];
this.state.tree_data = treeData //節(jié)點值賦值給state 的tree_data;
return(
<div>
<Search style={{ marginBottom: 8 }} placeholder="search" onChange={this.SearchChange} /> //搜索框
<DirectoryTree
multiple //支持點選多個節(jié)點(節(jié)點本身)boolean類型束昵;
onSelect={this.onSelect} //點擊樹節(jié)點觸發(fā)拔稳;
selectedKeys={this.state.select_treenodes} //(受控)設置選中的樹節(jié)點;
// 展開指定的樹節(jié)點
expandedKeys={this.state.expandFlag} //(受控)展開指定的樹節(jié)點(注意,這個一定要與onExpand一起用锹雏,不然不能關閉和展開樹節(jié)點巴比;
onExpand={this.onExpand} // 展開/收起節(jié)點時觸發(fā);
treeData={treeData} /> //數(shù)據(jù)
</div>
)
}
}