//最顶级的节点信息
import React from 'react'
import Tree from './Tree'
const treeData=[
{
title: '父节点1',
key: '0-0',
children: [
{
title: '子节点1',
key: '0-0-1',
children: [
{
title: '孙子节点',
key: '0-0-1-0',
children:[]
},
],
},
{
title: '子节点2',
key: '0-0-2',
children: [
],
},
],
},
{
title: '父节点2',
key: '1-0',
children: [
]
}
]
export default function Home() {
return (
<div>
<Tree data={treeData}></Tree>
</div>
)
}
//主要的级数划分
import React,{Fragment} from 'react'
import TreeNode from './TreeNode'
let lever=1;//这个代表当前是第几级
function Tree({data}) {
return (
<div>
{data.length&&data.map((v,i)=>{
return <TreeNode lever={lever} menus={v} key={i}></TreeNode>
})}
</div>
)
}
export default Tree;
//实际完成TreeNode组件
import React,{useState,Fragment} from 'react'
import './index.css'
export default function TreeNode({menus,lever}) {
const [isVisable,setisVisable]=useState(false)
//这个是控制显示打开关闭
const handleClick=()=>{
setisVisable((preState)=>preState=!preState)
}
return (
<div>
<div className={`TreeNOde${lever++}`} onClick={handleClick}> {menus.title}</div>
<div style={{display:isVisable?'block':'none'}}>
{menus.children.length>=1&&menus.children.map((v)=>{
return <TreeNode lever={lever++} menus={v} key={v.key}></TreeNode>
} )}
</div>
</div>
)
}
|