React权限高阶组件

权限设置

背景

项目中,设置权限通常有二种

菜单级权限
页面级权限

菜单级设置相对简单,可以在统一入口中处理。
页面级权限,组件场景较多,参考了线上的案例,完善了wrapAuth组件在项目中的应用

wrapAuth

/**
 * 权限 高阶组件
 * @param {reactNode} ComposedComponent 需要权限控制的组件
 * @param {string} path 页面pathname
 * @param {string} operCodes 操作web key,暂时用opercode
 * 使用说明:
 * 以下使用的 user 为固定不变,加载项目时,会直接加载opercode
 * @connect(({ user }) => ({
 *   user: user,
 * }))
 * render ....
 * // 引用 user已有的opercode
 * const {user: {userAllAuthRoleList: {operCode = []}}} = this.props;
 
 * // Button 案例
 * const AuthButton = WrapAuth(Button, operCode);
 * 搜索
 * or 搜索

 * // 自定义案例
 * const AuthSpan = WrapAuth(YgSpan, operCode);
 * 
 * 
 * function YgSpan(props) {
 *  
 *  return (
 *    
 *      测试消息
 *    
*   );
* }

 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';

const wrapAuth = (ComposedComponent, operCodes = [], path = '') => class WrapComponent extends Component {
  // 构造
  constructor(props) {
    super(props);
    this.state = {
      operCode: props.operCode,
      specialCode: props.specialCode,
    };
  }

  checkBtnAuth(operCode, specialCode = '') {
    const hasAuth = !!operCode && operCode.length > 0 ? operCodes.includes(operCode) : true;
    // console.log(operCodes, operCode, hasAuth);
    return hasAuth;
  }

  static propTypes = {
    operCode: PropTypes.string.isRequired, // 按钮级的权限webKey
    specialCode: PropTypes.string,
  };

  render() {
    const {operCode, specialCode, ...others} = this.props;
    if (this.checkBtnAuth(operCode, specialCode)) {
      return ;
    } else {
      return null;
    }
  }
};

export default wrapAuth;

Demo 实例

import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Table, Button, Icon } from 'ygd';
import WrapAuth from '@/components/Authorized/WrapAuth';

function YgSpan() {
  return (
    如不勾选,默认导出全部
  );
}
@connect(({ user }) => ({
  user,
}))
class Demo extends Component {

render() {
    const {user: {userAllAuthRoleList: {operCode = []}}} = this.props;
    const AuthButton = WrapAuth(Button, operCode);
    const AuthSpan = WrapAuth(YgSpan, operCode);

    return (
      
        
导出
); } } export default Demo;

你可能感兴趣的:(React权限高阶组件)