react+antd 使用Tree插件实现账号角色组权限功能

有一个用react写的后台管理系统,需要给账号赋予不同的角色组,角色组代表着不同的权限。antd中的Tree插件可以实现权限的显示获取。

<Tree
    checkable
    onCheck={this.onCheck.bind(this)}  // 选择事件
    onExpand={this.onExpand.bind(this)}  // 展开事件
    treeData={ruleList}  // 内容显示
/>


比较麻烦的时候,如果只选择了增删查改子节点,是不会将父节点也自动选择的,所以需要自己在事件中进行处理。可以在info中获取父节点,然后赋值给一个变量。

// 展开
onExpand=(expandedKeys) => {
    let _this = this
    _this.setState({
        expandedKeys
    })
};

// 选择
onCheck = (checkedKeys, info) => {
    let _this = this
    _this.formBox.current.setFieldsValue({
        rules: checkedKeys
    });
    _this.setState({
        checkedKeysFather: info.halfCheckedKeys
    })
};

最后在提交的时候对变量进行处理即可。

添加的全部代码:

import React, { Component } from 'react';
import { withRouter } from "react-router-dom";
import { Button, message, Form, Input, Tree } from 'antd';
import {  } from '@ant-design/icons';
import { addRule } from '../../../static/js/api';
import {  } from '../../../static/js/file';
import {  } from '../../../static/js/cookie';
import { InsertWrapper } from './style.js';
const rules = [{ required: true }];

class insertRule extends Component {
	constructor(props){
		super(props);
		this.state = {
            ruleList: [],  // 全部列表
			checkedKeys: [],  // 选中节点,不包括父节点
			expandedKeys: [],  // 展开节点
			checkedKeysFather: [],  // 选中节点,包括父节点
		}
	}

    formBox = React.createRef();
	// 查询全部权限
	getRule(){
		let list = JSON.parse(sessionStorage.getItem("eng_rule"))
		if(list.length>0){
			for(let i=0;i<list.length;i++){
				list[i].key = list[i].id.toString()
				if(list[i].children.length>0){
					for(let j=0;j<list[i].children.length;j++){
						list[i].children[j].key = list[i].children[j].id.toString()
                        if(list[i].children[j].children){
                            for(let k=0;k<list[i].children[j].children.length;k++){
                                list[i].children[j].children[k].key = list[i].children[j].children[k].id.toString()
                            }
                        }
					}
				}
			}
		}
		this.setState({
			ruleList: list
		})
	};

	// 展开
	onExpand=(expandedKeys) => {
		let _this = this
		_this.setState({
			expandedKeys
		})
	};
	// 选择
	onCheck = (checkedKeys, info) => {
		let _this = this
		_this.formBox.current.setFieldsValue({
			rules: checkedKeys
		});
		_this.setState({
			checkedKeysFather: info.halfCheckedKeys
		})
	};
	// 保存
	InsertFinish(values){
        let _this = this
		let father = _this.state.checkedKeysFather
		if(father.length===0){
		}else{
			for(let i=0;i<father.length;i++){
				values.rules.push(father[i])
			}
		}
	};

	// 渲染
	componentDidMount(){
		this.getRule()
	};
	
	render() {
        const { ruleList } = this.state;
		return (
			<InsertWrapper>
                <Form ref={this.formBox} name="update-ref" onFinish={this.InsertFinish.bind(this)} layout='horizontal'>
                    <Form.Item name="name" label="名称" rules={rules}>
                        <Input placeholder="请输入名称" autoComplete="off" />
                    </Form.Item>
                    <Form.Item name="rules" label="规则" rules={rules}>
                        <Tree
                            checkable
							onCheck={this.onCheck.bind(this)}
							onExpand={this.onExpand.bind(this)}
                            treeData={ruleList}
                        />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">
                            保存
                        </Button>
                    </Form.Item>
                </Form>
			</InsertWrapper>
		);
	}
}

export default withRouter(insertRule);

编辑的全部代码:

import React, { Component } from 'react';
import { withRouter } from "react-router-dom";
import { Button, message, Form, Input, Tree, Spin } from 'antd';
import {  } from '@ant-design/icons';
import { detailRule, updateRule } from '../../../static/js/api';
import {  } from '../../../static/js/file';
import {  } from '../../../static/js/cookie';
import { InsertWrapper } from './style.js';
const rules = [{ required: true }];

class insertRule extends Component {
	constructor(props){
		super(props);
		this.state = {
			loading: true,  // 懒加载
			id: '',
            ruleList: [],  // 全部列表
			checkedKeys: [],  // 选中节点,不包括父节点
			expandedKeys: [],  // 展开节点
			checkedKeysFather: [],  // 选中节点,包括父节点
		}
	}

    formBox = React.createRef();
	// 查询全部权限
	getRule(){
		let list = JSON.parse(sessionStorage.getItem("eng_rule"))
		if(list.length>0){
			for(let i=0;i<list.length;i++){
				list[i].key = list[i].id.toString()
				if(list[i].children.length>0){
					for(let j=0;j<list[i].children.length;j++){
						list[i].children[j].key = list[i].children[j].id.toString()
                        if(list[i].children[j].children){
                            for(let k=0;k<list[i].children[j].children.length;k++){
                                list[i].children[j].children[k].key = list[i].children[j].children[k].id.toString()
                            }
                        }
					}
				}
			}
		}
		this.setState({
			ruleList: list
		})
	};

	// 获取详情
	getDetail(id){
		let _this = this
		let postData = {
			id
		}
		detailRule(postData).then(res=>{
			if(res.code===1){
				let rulesKey = ''
				let checkedKeysFather = []
				if(res.data.rules===null){
					rulesKey = ''
				}else{
					rulesKey = res.data.rules.split(',')
					for(let i=0;i<_this.state.ruleList.length;i++){
						for(let j=0;j<rulesKey.length;j++){
							if(_this.state.ruleList[i].id.toString()===rulesKey[j]){
								checkedKeysFather.push(rulesKey.splice(j, 1)[0])
							}
						}
					}
				}
				console.log(rulesKey)
				_this.formBox.current.setFieldsValue({
					name: res.data.name,
					rules: rulesKey
				});
				_this.setState({
					checkedKeys: rulesKey,
					checkedKeysFather,
					id,
					loading: false
				})
			}
		})
	};

	// 展开
	onExpand=(expandedKeys) => {
		let _this = this
		_this.setState({
			expandedKeys
		})
	};
	// 选择
	onCheck = (checkedKeys, info) => {
		let _this = this
		let father = []
		if(info.checked===false){
			father = info.halfCheckedKeys
		}else{
			if(info.halfCheckedKeys){
				if(info.halfCheckedKeys.length===0){
					father = []
				}else{
					father = info.halfCheckedKeys
				}
			}else{
				father = []
			}
		}
		_this.formBox.current.setFieldsValue({
			rules: checkedKeys
		});
		_this.setState({
			checkedKeys,
			checkedKeysFather: father
		})
	};
	// 保存
	InsertFinish(values){
        let _this = this
		let father = _this.state.checkedKeysFather
		if(father.length===0){

		}else{
			for(let i=0;i<father.length;i++){
				values.rules.push(father[i])
			}
		}
	};

	// 渲染
	componentDidMount(){
		this.getRule()
		this.getDetail(this.props.comment)
	};
	UNSAFE_componentWillReceiveProps(nextProps) {
		this.getRule()
		if(this.props.comment === nextProps.comment){
            this.getDetail(this.props.comment)
		}else{
			// 重新调用接口
			this.getDetail(nextProps.comment)
		}
		return true;
	}
	
	render() {
        const { ruleList, checkedKeys, expandedKeys, loading } = this.state;
		return (
			<InsertWrapper>
				<Spin spinning={loading}>
					<Form ref={this.formBox} name="update-ref" onFinish={this.InsertFinish.bind(this)} layout='horizontal'>
						<Form.Item name="name" label="名称" rules={rules}>
							<Input placeholder="请输入名称" autoComplete="off" />
						</Form.Item>
						<Form.Item name="rules" label="规则" rules={rules}>
							<Tree
								checkable
								checkedKeys={checkedKeys}
								expandedKeys={expandedKeys}
								onCheck={this.onCheck.bind(this)}
								onExpand={this.onExpand.bind(this)}
								treeData={ruleList}
							/>
						</Form.Item>
						<Form.Item>
							<Button type="primary" htmlType="submit">
								保存
							</Button>
						</Form.Item>
					</Form>
				</Spin>
			</InsertWrapper>
		);
	}
}

export default withRouter(insertRule);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值