[英]How to make a component visible/available only for few set of users in react?
我有一种情况,我只需要向管理员显示组件而不向普通用户显示组件。
说,
<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概念的东西。 任何帮助表示赞赏。
您可以编写基于角色的组件并将其用作包装器。
RoleBasedComponent.js
const RoleBasedComponent = ({ children, supportedRoles, role }) => {
return (
<div>
{supportedRoles.indexOf(role) > -1 ? children : <h2>Access Denied</h2>}
</div>
);
};
export default RoleBasedComponent;
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>
);
}
怎么样:
{!isAdmin && <ChildTwo />}
您可以简单地将三元数放入JSX中:
render () {
return (
<Parent>
<ChildOne />
{this.props.isAdmin ? <ChildTwo /> : null}
<ChildThree />
</Parent>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.