首页 > 解决方案 > 如何使组件仅对少数响应的用户可见/可用?

问题描述

我有一个场景,我需要只向管理员而不是普通用户显示一个组件。

说,

<Parent>
  <ChildOne />
  <ChildTwo />     // This component should be rendered for public users.
  <ChildThree />
</Parent>

我已经尝试过的

我将 isAdmin 属性从父级传递给子级,以确定组件是否可见状态。

 const ChildTwoComp =  props.isAdmin ? <ChildTwo /> : null
 render () {
   return (
     <Parent>
       <ChildOne />
       {ChildTwoComp}    
       <ChildThree />
     </Parent>
    )
  }

我不认为我做得对。有没有其他更好的解决方案或正确的方法来做到这一点。

我想要类似于 Reactjs 中的 PrivateRoute 概念的东西。任何帮助表示赞赏。

标签: javascriptreactjs

解决方案


您可以编写基于角色的组件并将其用作包装器。

RoleBasedComponent.js

const RoleBasedComponent = ({ children, supportedRoles, role }) => {
  return (
    <div>
      {supportedRoles.indexOf(role) > -1 ? children : <h2>Access Denied</h2>}
    </div>
  );
};

export default RoleBasedComponent;

应用程序.js

function App() {
  return (
    <RoleBasedComponent
      role={"admin"}
      supportedRoles={["admin", "support_admin", "user"]}
    >
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
      </div>
    </RoleBasedComponent>
  );
}

这是演示https://codesandbox.io/s/ql9p2q0kxq


推荐阅读