数据
export const data = [
{
name: "111",
title: "111",
children: [{
name: "test",
title: "test",
children: [{
name: "test1",
title: "test2",
}]
}]
},
{
name: "222",
title: "222",
children: [{
name: "test",
title: "test",
children: [{
name: "test4",
title: "test5",
}]
}]
},
{
name: "333",
title: "333"
}
];
缩进函数和递归渲染函数
nbsp = (index) => {
let temp = [];
for (let i = 0; i < index; i++) {
temp.push(<span key={i}> </span>)
}
return <span>{temp}</span>
};
renderTree = (data, index = 0) => {
let that = this;
index++;
return <div>
{
data ? data.map((item) => {
if (item.children && item.children[0]) {
return <div>
<span>{that.nbsp(index)}{item.title}</span>
{that.renderTree(item.children, index)}
</div>;
} else {
return <div>
<div>{that.nbsp(index)}{item.title}</div>
</div>
}
}) : null
}
</div>
};
调用树函数
render(){
let that = this;
return <div>{that.renderTree(data)}</div>
}
整体示例代码
import * as React from "react";
export const data = [
{
name: "111",
title: "111",
children: [{
name: "test",
title: "test",
children: [{
name: "test1",
title: "test2",
}]
}]
},
{
name: "222",
title: "222",
children: [{
name: "test",
title: "test",
children: [{
name: "test4",
title: "test5",
}]
}]
},
{
name: "333",
title: "333"
}
];
export class Tree extends React.Component{
nbsp = (index) => {
let temp = [];
for (let i = 0; i < index; i++) {
temp.push(<span key={i}> </span>)
}
return <span>{temp}</span>
};
renderTree = (data, index = 0) => {
let that = this;
index++;
return <div>
{
data ? data.map((item) => {
if (item.children && item.children[0]) {
return <div>
<span>{that.nbsp(index)}{item.title}</span>
{that.renderTree(item.children, index)}
</div>;
} else {
return <div>
<div>{that.nbsp(index)}{item.title}</div>
</div>
}
}) : null
}
</div>
};
render() {
let that = this;
return <div>{that.renderTree(data)}</div>
}
}
实现效果