递归生成antd的TreeSelect或者Tree的树子节点
以下是初始数据格式
data: [
{
code: '1', childrenList: [
{
code: '1-1', childrenList: [
{ code: '1-1-1', childrenList: [] },
{ code: '1-1-2', childrenList: [] }
]
}
]
},
{
code: 2, childrenList: [
{
code: '2-1', childrenList: [
{ code: '2-1-1', childrenList: [] }
]
},
{
code: '2-2', childrenList: [
{ code: '2-2-1', childrenList: [] }
]
}
]
},
{ code: '3', childrenList: [] }
]
数据中的 childrenList 即为下一层的子节点
数据结构一共含有三层,最终递归生成的Tree如下图
递归的实现方法如下
/**
* 递归生成数据
* @param {Object} data 原始数据
*/
renderTreeNode = data => data.map(element => {
if (element.childrenList.length > 0) {
return <TreeNode
title={element.code}
value={element.code}
key={element.code}
>
{this.renderTreeNode(element.childrenList)}
</TreeNode>
} else {
return <TreeNode
title={element.code}
value={element.code}
key={element.code}
/>
}
})
本demo完整的代码如下
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { TreeSelect } from 'antd';
const { TreeNode } = TreeSelect;
class Demo extends React.Component {
constructor(props){
super(props)
this.state = {
// 初始数据
data: [
{code:'1', childrenList:[
{code:'1-1', childrenList:[
{code:'1-1-1', childrenList:[]},
{code:'1-1-2', childrenList:[]}
]}
]},
{code:2, childrenList:[
{code:'2-1', childrenList:[
{code:'2-1-1', childrenList:[]}
]},
{code:'2-2', childrenList:[
{code:'2-2-1', childrenList:[]}
]}
]},
{code:'3', childrenList:[]}
]
}
}
/**
* 递归生成数据
* @param {Object} data 原始数据
*/
renderTreeNode = data => data.map(element => {
if (element.childrenList.length > 0) {
return <TreeNode
title={element.code}
value={element.code}
key={element.code}
>
{this.renderTreeNode(element.childrenList)}
</TreeNode>
} else {
return <TreeNode
title={element.code}
value={element.code}
key={element.code}
/>
}
})
render() {
const {data} = this.state
// 生成数据
const treeNode = this.renderTreeNode(data)
return (
<TreeSelect
style={{ width: '300px' }}
value={this.state.value}
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
placeholder="Please select"
treeDefaultExpandAll
>
{treeNode.length > 0 && treeNode}
</TreeSelect>
);
}
}
ReactDOM.render(<Demo />, document.getElementById('root'));