树形组件涉及到层层递归的模式,因此需要用到深度优先遍历dfs, 树的数据结构在前端开发中十分重要。
代码案例:
const { Tree } = antd
const { TreeNode } = tree
const json = [
{
title: "一",
key: "1",
children:[{title:"三", key: "3", children:[
{title:"五", key: "5", children:[]
]}]
},
{
title: "二",
key: "2",
children:[{title:"四", key:"4", children:[]}]
}
]
class Demo extends React.Component {
dfs = (n) => {
return (
<TreeNode title = {n.title} key = {n.key}>
{n.children.map(this.dfs)}
</TreeNode>
)
}
render() {
return (
<Tree>
{json.map(this.dfs)}
</Tree>
)
}
}
export default Demo
代码结果: