我正在构建一个ReactJS应用程序(我的第一个),我需要隐藏部分页面,因为授权。
例如,我左边有一个菜单,有些li
应该在授权之下。
现在我没有为此目的找到一些API,只是#34;登录"。
例如:
<ul>
<authorization hasRole="simple_user">
<li>Read Post</li>
</authorization>
<authorization hasRole="registerd_user">
<li>Create Post</li>
</authorization>
<authorization hasRole="admin_user">
<li>Delete Post</li>
</authorization>
</ul>
答案 0 :(得分:2)
您可以使用switch
声明。
class HideMe extends React.Component {
constructor(){
super();
this.state = {
isAuthorized: false,
role: ''
};
this.checkAuto = this.checkAuto.bind(this);
this.autorization = this.autorization.bind(this);
}
checkAuto(e){
// of course you should send some request to the server
// and i just simulate it : "admin", "user", "SEO"
console.log(e.target.value)
switch(e.target.value) {
case 'admin':
this.setState({isAuthorized: true, role: 'admin'});
break;
case 'user':
this.setState({isAuthorized: true, role: 'user'});
break;
case 'SEO':
this.setState({isAuthorized: true, role: 'SEO'});
break;
default:
this.setState({isAuthorized: false, role: ''});
break;
}
}
autorization(){
console.log(this.state.isAuthorized, this.state.role)
if (this.state.isAuthorized && this.state.role === "admin")
return <div className="admin">This is Admin</div>
if (this.state.isAuthorized && this.state.role === "SEO")
return <div className="seo">This is SEO</div>
if (this.state.isAuthorized && this.state.role === "user")
return <div className="user">This is user</div>
else
return <div className="notuser">not Authorized</div>
}
render(){
return <div>
<label>Simulate autorization: <input type="text" onChange={this.checkAuto}/> </label>
<hr/>
{this.autorization()}
</div>
}
}
React.render(<HideMe />, document.getElementById('container'));
fiddle示例。我希望它会对你有所帮助。
由于
答案 1 :(得分:0)
授权组件可以如下
<ul><authorization role="simple_user" /></ul>
可以按如下方式返回
////////////
return (
<div>
{(() => {
switch (this.props.role){
case "simple_user":
return <li>Read Post</li>;
case "registered_user":
return <li>Create Post</li>;
case "admin_user":
return <li>Delete Post</li>;
default:
return <li>Read Post</li>;
}
})()}
</div>
);