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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章