antd根据数据递归生成树节点

2020-07-10 22:37 插件 1499 0
递归生成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<TreeNodetitle={element.code}value={element.code}key={element.code}>{this.renderTreeNode(element.childrenList)}</TreeNode>}else{return<TreeNodetitle={element.code}value={element.code}key={element.code}/>}})本demo完整的代码如下importReactfrom'react';importReactDOMfrom'react-dom';import'antd/dist/antd.css';import'./index.css';import{TreeSelect}from'antd';const{TreeNode}=TreeSelect;classDemoextendsReact.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<TreeNodetitle={element.code}value={element.code}key={element.code}>{this.renderTreeNode(element.childrenList)}</TreeNode>}else{return<TreeNodetitle={element.code}value={element.code}key={element.code}/>}})render(){const{data}=this.state//生成数据consttreeNode=this.renderTreeNode(data)return(<TreeSelectstyle={{width:'300px'}}value={this.state.value}dropdownStyle={{maxHeight:400,overflow:'auto'}}placeholder="Pleaseselect"treeDefaultExpandAll>{treeNode.length>0&&treeNode}</TreeSelect>);}}ReactDOM.render(<Demo/>,document.getElementById('root'));
暂无评论,我会出手
说点什么
登录用户可以修改和删除评论,可以收到回复的邮件提醒点击登录/注册
最多上传8张图片,仅支持jpg,png格式图片,单张大小5MB以内!
用户名: