我想要创建一个进行安全检查的React组件,如果它通过了,它将呈现出它的子组件,如果它失败了,它就不会呈现任何东西。
我已经搭建了一个像这样的组件:
var RolesRequired = React.createClass({
permitted: roles => ...,
render: function () {
if (!this.permitted(this.props.roles)) {
return null;
}
return this.props.children;
}
});我计划的用法如下:
<RolesRequired roles={['admin']}>
<h1>Welcome to the admin</h1>
<div>
Admin stuff here
</div>
</RolesRequired>如何从RolesRequired组件返回所有子组件?
发布于 2015-07-14 20:14:27
我认为高阶组件也是一个很好的选择。基本上,您可以将定义某些行为并决定是否应该呈现包装的任何组件封装在临时组件中。
最好的方法是在启用了一些ES2015特性(即装饰器)的情况下使用ES2016转发器:
function withRoles(roles) {
return function(Component) {
return class ComponentWithRoles extends React.Component {
constructor(props) {
super(props)
// Not sure where the data to get your roles about current user?
// from but you could potentially to that here if I'm getting your point
// and also setup listeners
this.state = { currentUser: 'admin' }
}
validateRoles() {
// you have access to the ``roles`` variable in this scope
// you can use it to validate them.
return true;
}
render() {
if (this.validateRoles()) {
return <Component {...this.props} />;
)
} else {
return <div>Nope...</div>;
}
}
}
}
}
// You can then use this on any component as a decorator
@withRoles({ showOnlyFor: [ 'admin' ] })
class AdminOnlyComponent extends React.Component {
render() {
return <div> This is secert stuff </div>
}
}我使用了ES2016特性,因为我认为更好地理解这一点,但是您可以通过简单的函数包装来实现它,下面是一个核心成员关于https://gist.github.com/sebmarkbage/ef0bf1f338a7182b6775这个主题的要点
发布于 2015-02-25 00:21:24
我想出了一个解决方案:
var RolesRequired = React.createClass({
permitted: roles => ...,
render: function () {
if (!this.permitted(this.props.roles)) {
return null;
}
return <div>{this.props.children}</div>;
}
});我正在做的是将被返回的子元素包装在一个<div>中,但是我必须添加一个不需要的/不需要的DOM元素来实现它。
https://stackoverflow.com/questions/28708936
复制相似问题