根据反应中的角色权限隐藏或显示组件的元素

Hide or show element of a component based on role permission in react

我想 show/hide 元素出现在组件中,基于角色级别权限, 这是我到目前为止尝试过的代码

我的组件:

   <ShowForPermission permission="My Studies" configuration={configuration}>
  <div>Mystudies</div>
   <ShowForPermission>

HOC:

import React from 'react'

export const ShowForPermission = ({ permission, configuration}) => {

    
    const isAllowed = checkPermission(permission, configuration);

     return isAllowed
     
    
  }

  export const checkPermission = (permission, configuration) => {
   
    return configuration&&configuration.filter((item)=>item.name===permission)[0].permission.read
}

在我的组件中,我将密钥作为 My Studies 传递,并将该特定组件的角色配置作为 configuration 传递给 ShowForPermission 在 HOC 中,我正在检查给定的键,即权限“我的研究”等于 configuration.filter((item)=>item.name==="My Studies") 所以我正在检查的是假设这个值是否为真,我想在我的组件中呈现 div 否则不。如何实现这一目标。请帮我解决这个问题

if permission.read==true, return true else false 并根据条件渲染 div。

谢谢

您所描述的不是 HOC。很好,组件组合(当您嵌套组件以显示在另一个提供控制的组件中时)比这里的 HOC 更适合。

因此您的 ShowForPermission 进行一些检查并呈现提供的任何嵌套组件(嵌套组件作为 children prop 传递)

export const ShowForPermission = ({ permission, children }) => {
  const isAllowed = ..... // do some permission check
  if (isAllowed) {
    return children; // rendering nested elements
  } else {
    /*
     it also might be false, empty string or empty array
     (and for React 18 it can be `return;` or `return undefined` as well);
     also you even can omit explicit `return undefined;` for `else` branch
     but this way intention is more clear
    */
    return null; 
  }
}

但是如何获得configuration?绝对不会将其作为道具传递。为什么?因为你每次用ShowForPermission的时候都需要传过去。要在第 3、5 或 10 级嵌套组件中传递它,您必须将 configuration 传递给它的每个父级。其名称为“道具钻井”,Context API 正是为解决此问题而创建的。

Context API 是一种将数据注入组件的方法,无需将其作为 prop 显式传递给每个父组件。查看文档中的示例,最后您的应用程序应该加载配置并在最根应用程序元素或接近根的某处创建 <YourContextProvider value={configurationData}> 。我有意跳过如何在传递给上下文之前加载该配置的问题(一个大的单独主题,也符合您的要求)。

最后,您的 ShowForPermission 将从上下文访问数据(最好使用 useContext 挂钩)以检查权限:

export const ShowForPermission = ({ permission, children }) => {
  const configuration = useContext(YourPermissionContext);
  const isAllowed = configuration
    .filter(
      (item) => item.name===permission
    )[0].permission.read;

  if (isAllowed) {
    return children; // rendering nested elements
  } else {
    return null; 
  }
}