react页面元素权限控制

// 当前页面的元素权限集合
const array = ["transaction_report_download"]; 
// 把从后端传过来的权限数组存储在cookies中,在当前页面获取cookies中存储的信息
const array1 = JSON.parse(Cookies.get("auth")); 
// 数组比对取出当前页面权限
const auths = [];
for (let i = 0; i < array.length; i++) {
    for (let j = 0; j < array1.length; j++) {
        if (array[i] === array1[j]) {
            auths.push({
                auth: array[i],
            });
        }
    }
}
// console.log(auths)
// console.log(array)
// console.log(array1)

function checkAuth(auth) {
    // 用户权限表
    const rules = auths;
    for (let i = 0; i < rules.length; i++) {
        const item = rules[i];
        // 无需权限控制或者权限匹配则通过
        if (!auth || auth === item.auth) {
            return true;
        }
    }
    return false;
}
// 高阶组件包装原组件
function wrapAuth(WrappedComponent) {
    let New = class extends React.Component {
        // constructor(props) {
        //     super(props);
        // }

        render() {
            if (checkAuth(this.props.auth)) {
                return <WrappedComponent {...this.props} />;
            } else {
                return null;
            }
        }
    };
    return New;
}
let AuthButton = wrapAuth(Button);
<AuthButton
    style={{ marginLeft: "10px" }}
    type="primary"
    htmlType="submit"
    icon="download"
    auth="transaction_report_download"
>
    下载报表
</AuthButton>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章