[英]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.