antd-树形组件常用工具

52次阅读

共计 4434 个字符,预计需要花费 12 分钟才能阅读完成。

treeUtil.js

import {Tree,message,Button,Input} from 'antd';
import React from 'react'
import axios from 'axios'
const {TreeNode} = Tree;
const Search = Input.Search;


const getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {const node = tree[i];
        if (node.children) {if (node.children.some(item => item.key === key)) {parentKey = node.key;} else if (getParentKey(key, node.children)) {parentKey = getParentKey(key, node.children);
            }
        }
    }
    return parentKey;
};
const dataList = [];
const generateList = (data) => {for (let i = 0; i < data.length; i++) {const node = data[i];
        const key = node.key;
        dataList.push({key, title: node.title});
        if (node.children) {generateList(node.children);
        }
    }
};
export default class treeUtil extends React.Component{constructor(props) {super(props);
        this.state = {treeData:[]
        };

    }
    componentWillMount (){this.getTree();
    }
    getTree(){axios.get(this.props.treeurl).then(res =>{generateList(res.data.data)
            this.setState({
                treeData:res.data.data,
                haveTreeData:true,
                expandedKeys: [],
                searchValue: '',
                autoExpandParent: true,
            })

        })
    }
    onExpand = (expandedKeys) => {
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    }
    onSelect = (selectedKeys) => {console.log(this.props)

        // this.formRef.setState({
        //     disabled:true
        // })
        this.setState({selectedKeys});
        if(selectedKeys.length>0 && this.props.selectMethod){this.props.selectMethod(selectedKeys)
        }
    }

    onChange = (e) => {
        const value = e.target.value;
        const newExpandedKeys = []
        let expandedKeys = dataList.map((item) => {if (item.title.indexOf(value) > -1) {return getParentKey(item.key, this.state.treeData);
            }
            return null;
        }).filter((item, i, self) => item && self.indexOf(item) === i);

        expandedKeys.forEach(x=>{newExpandedKeys.push(x.toString())
        })
        this.setState({
            expandedKeys:newExpandedKeys,
            searchValue: value,
            autoExpandParent: true,
        });

    }
    onCheck = (checkedKeys) => {console.log('onCheck', checkedKeys);
        if(checkedKeys.length>0 && this.props.checkMethod){this.props.checkMethod(checkedKeys)
        }
        this.setState({checkedKeys});
    }


    renderTreeNodes = data => data.map((item) => {if (item.children) {
            return (<TreeNode title={item.title}  key={item.key} dataRef={item}>
                    {this.renderTreeNodes(item.children)}
                </TreeNode>
            );
        }
        return <TreeNode {...item} />;
    })

    addTree(){
        // // 解除禁用
        // this.formRef.setState({
        //     disabled:false
        // })
        let selectedKey = null;
        if(this.state.selectedKeys){selectedKey= this.state.selectedKeys[0]
        }else {selectedKey = null;}

    }
    change(){
        // this.formRef.setState({
        //     disabled:false
        // })
    }
    delete(){axios.get(this.props.deleteUrl+this.state.selectedKeys[0] ).then(res =>{if(res.data.success){message.success(res.message);
                this.getTree()
                this.formRef.props.form.resetFields();}else{message.warning("系统异常");
            }


        })
    }
    render(){const { searchValue, expandedKeys, autoExpandParent} = this.state;
        const loop = data => data.map((item) => {const index = item.title.indexOf(searchValue);
            const beforeStr = item.title.substr(0, index);
            const afterStr = item.title.substr(index + searchValue.length);
            const title = index > -1 ? (
                <span>
                    {beforeStr}
                    <span style={{color: 'blue'}}>{searchValue}</span>
                    {afterStr}
        </span>
            ) : <span>{item.title}</span>;
            if (item.children) {
                return (<TreeNode key={item.key} title={title}>
                        {loop(item.children)}
                    </TreeNode>
                );
            }
            return <TreeNode key={item.key} title={title} />;
        });
        return(
            <div>
                {this.props.button?
                    <div className="btn-group">
                        {this.props.button.includes("add")?<Button type="primary" onClick={this.addTree.bind(this)}> 添加 </Button>:""}
                        {this.props.button.includes("update")?<Button type="primary" onClick={this.change.bind(this)}> 修改 </Button>:""}
                        {this.props.button.includes("delete")?<Button type="primary" onClick={this.delete.bind(this)}> 删除 </Button>:""}

                    </div>:""

                }
                {this.props.searchable?<Search style={{ marginBottom: 8}} placeholder="搜索" onChange={this.onChange} />:""}

                <Tree
                    onExpand={this.onExpand}
                    expandedKeys={this.state.expandedKeys}
                    autoExpandParent={this.state.autoExpandParent}
                    onSelect={this.onSelect}
                    selectedKeys={this.state.selectedKeys}
                    checkable = {this.props.checkable}
                >
                    {loop(this.state.treeData)}


                </Tree>
            </div>
            )


    }
}
 调用
 const treeOption = {
    treeurl:React.rootDirectoryUrl+"/department/getDepartmentTree",// 地址
    selectMethod:this.onSelect, // 选择方法
    checkMethod:this.onCheck ,//chect 方法
    button:["add","update","delete"],// 显示哪些按钮
    checkable:true,// 可 check
    searchable:true,// 可搜索

}


<TreeUtil
    {...treeOption}
/>

数据类型

{
"code":"200",
"message":"获取成功",
"data":[
    {
     "key":45,
     "title":"公司",
     "pid":null,
     "children":[
         {
             "key":46,
             "title":"研发部",
             "pid":45,
             "children":[
                 {
                     "key":48,
                     "title":"产品 1",
                     "pid":46,
                     "children":[]},{
                     "key":49,
                     "title":"产品 2",
                     "pid":46,
                     "children":[]}
              ]
         },{
             "key":50,
             "title":"财务部",
             "pid":45,
             "children":[
                 {
                     "key":52,
                     "title":"会计",
                     "pid":50,
                     "children":[]}
                 
             ]
          }
     ]
  },{
       "key":53,
       "title":"外包",
       "pid":null,
       "children":[{"key":54,"title":"科技部","pid":53,"children":[]}
       ]
     }
     ],"success":true}

正文完
 0