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



我想根据角色级别权限显示/隐藏组件中存在的元素,这是我到目前为止尝试的代码

我组件:

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

的:

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
}

这里在我的组件我传递键为我的研究该特定组件的角色配置为configurationShowForPermission在HOC中,我检查给定的关键字即permission "My studies"等于configuration.filter((item)=>item.name==="My Studies"),所以我检查s假设如果这个值为真,我想渲染div存在于我的组件或其他没有。如何做到这一点。请帮我解决这个问题

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

感谢

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

所以你的ShowForPermission做一些检查,并呈现任何嵌套组件提供(嵌套组件传递作为childrenprop)

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传递给每一个它的父组件。它的名字是"道具钻井"和上下文API正是为了解决这个问题而创建的。

Context API是一种将数据注入组件的方法,而无需将其作为prop显式地传递给每个父组件。看看文档中的例子,最后你的应用程序应该加载配置,并在最根app元素或接近根的某个地方创建<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; 
}
}