简体   繁体   English

如何使组件仅在少数用户集中可见/可用?

[英]How to make a component visible/available only for few set of users in react?

I have a scenario where i need to show a component only to the admins not for the regular users. 我有一种情况,我只需要向管理员显示组件而不向普通用户显示组件。

Say, 说,

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

What i have already tried 我已经尝试过的

I passed isAdmin prop from the parent to the child to determine whether the component visible status. 我将isAdmin属性从父级传递给子级,以确定组件是否可见。

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

I don't think I am doing it right. 我认为我做的不对。 Is there any other better solution or right way to do it. 还有其他更好的解决方案或正确的方法吗?

I want something similar to PrivateRoute concept in Reactjs. 我想要类似于Reactjs中的PrivateRoute概念的东西。 Any help appreciated. 任何帮助表示赞赏。

You can write a role based component and use it as a wrapper. 您可以编写基于角色的组件并将其用作包装器。

RoleBasedComponent.js RoleBasedComponent.js

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

export default RoleBasedComponent;

App.js App.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>
  );
}

Here is the demo https://codesandbox.io/s/ql9p2q0kxq 这是演示https://codesandbox.io/s/ql9p2q0kxq

怎么样:

{!isAdmin && <ChildTwo />}

You can simply put your ternary inside the JSX : 您可以简单地将三元数放入JSX中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM