src/page/TreePage.js
import React, { Component } from 'react'
import TreeNode from '../components/TreeNode';
//数据源
const treeData = {
key: 0, //标识唯一性
title: "全国", //节点名称显示
children: [
//子节点数组
{
key: 6,
title: "北方区域",
children: [
{
key: 1,
title: "黑龙江省",
children: [
{
key: 6,
title: "哈尔滨",
},
],
},
{
key: 2,
title: "北京",
},
],
},
{
key: 3,
title: "南方区域",
children: [
{
key: 4,
title: "上海",
},
{
key: 5,
title: "深圳",
},
],
},
],
};
export default class TreePage extends Component {
render() {
return (
<div>
<TreeNode data={treeData}/>
</div>
)
}
}
src/components/TreeNode.js
import React, { Component } from 'react'
export default class TreeNode extends Component {
constructor(props){
super(props);
this.state = {
expanded: false
}
}
render() {
//传进来的对象是data
const {title,children} = this.props.data;
const {expanded} = this.state;
const hasChildren = children && children.length > 0;
return (
<div>
<div className="nodeInner" onClick={()=>this.setState({expanded:!expanded})}>
{hasChildren && <i className={"tri " + (expanded ? "tri-open":"tri-close")}></i>}
<span>{title}</span>
</div>
{
hasChildren && expanded && <div className="children">
{
children.map(item => {
return <TreeNode key={item.key} data={item}/>
})
}
</div>
}
</div>
)
}
}
网友评论