UNPKG

yylib-quick-mobile

Version:

yylib-quick-mobile

118 lines (116 loc) 3.73 kB
import React from 'react' import { List, Radio,Icon } from 'antd-mobile'; import YYIcon from './../icon/YYIcon'; import './tree.less'; import classnames from 'classnames'; const RadioItem = Radio.RadioItem; const Item=List.Item; /****当前默认暂时只支持选择单个数据*****/ class YYTreeSelect extends React.Component { constructor(){ super(); this.state={ allData:[], selectItem:null } } componentDidMount(){ if(this.props.RunInDesign){ /*****如果是设计期间的数据*****/ this.setState({allData:[ {id:1,pid:"0",name:"嘉宏振兴大厦",open:true,isLeaf:false}, {id:2,pid:"0",name:"嘉宏振兴大厦保安部",open:true,isLeaf:false}, {id:3,pid:"2",name:"嘉宏振兴大厦行政部",open:true,isLeaf:true} ]}); } } selectChange(item,event){ event.stopPropagation(); this.setState({selectItem:item}); /******如果想要选择完成之后直接关闭 父级实现这个函数即可******/ if(this.props.selectChange){ this.props.selectChange(item) } } setData(Data){ if(Data&&Data.constructor==Array){ this.setState({allData:Data}) }else{ console.log("设置单选树的数据格式有误!") } } _getChildData(item){ if(this.props.loadChildData){ let appendData=this.props.loadChildData(item,(data)=>{ if(data&&data.constructor==Array){ let {allData}=this.state; allData.map(node=>{if(node.id==item.id){node.open=!item.open}}) allData=allData.concat(data) this.setState({allData:allData}) }else{ console.log("设置单选树子选项的数据格式有误"); } }); } } _clickItem(item,event){ event.stopPropagation(); if(!item.isLeaf){ let {allData}=this.state; if(!allData.some(dateItem=>dateItem.pid==item.id)){ /****懒加载开始******/ this._getChildData(item); }else{ /****只有非叶子节点才可以加载*****/ allData.map(node=>{if(node.id==item.id){node.open=!item.open}}) this.setState({allData:allData}) } } } _getTree(rootValue,show){ let {allData:list}=this.state; let {className}=this.props; let currentNode=[]; list.map((item,index)=>{ if(item.pid==rootValue){ let child; if(!item.isLeaf){ /****如果还有叶子节点****/ child=this._getTree(item.id,item.open) } let arrow=""; if(!item.isLeaf&&!item.open){ arrow="right"; } else if(!item.isLeaf&&item.open){ arrow="down"; } if(show){ let selected=this.state.selectItem&&this.state.selectItem.id==item.id; let childIcons=!item.isLeaf?"Org":"Fill"; currentNode.push(<Item key={index}> <Icon size="md" className="yy-lazy-tree-icon-openclose" type={arrow} color="#C7C7CC" onClick={this._clickItem.bind(this,item)} /> <RadioItem checked={selected} className={selected?"yy-lazy-tree-selectitem":""} onChange={this.selectChange.bind(this,item)}> <YYIcon type={childIcons} size="xxs" color="#414655" style={{"marginRight":"10px"}} />{item.name}</RadioItem> {child} </Item>) } } }); return currentNode; } render() { let {visible,className}=this.props; let wrapClz = classnames('yy-lazy-tree' ,(!visible&&'hidden'), className); return ( <List className={wrapClz}> {this._getTree("0",true)} </List> ) } } YYTreeSelect.defaultProps = { visible:true } export default YYTreeSelect;