首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在react.js中创建未呈现的包装组件。

在react.js中创建未呈现的包装组件。
EN

Stack Overflow用户
提问于 2015-02-25 00:19:43
回答 2查看 1.2K关注 0票数 2

我想要创建一个进行安全检查的React组件,如果它通过了,它将呈现出它的子组件,如果它失败了,它就不会呈现任何东西。

我已经搭建了一个像这样的组件:

代码语言:javascript
复制
var RolesRequired = React.createClass({
    permitted: roles => ...,

    render: function () {
        if (!this.permitted(this.props.roles)) {
            return null;
        }

        return this.props.children;
    }
});

我计划的用法如下:

代码语言:javascript
复制
<RolesRequired roles={['admin']}>
    <h1>Welcome to the admin</h1>
    <div>
        Admin stuff here
    </div>
</RolesRequired>

如何从RolesRequired组件返回所有子组件?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-07-14 20:14:27

我认为高阶组件也是一个很好的选择。基本上,您可以将定义某些行为并决定是否应该呈现包装的任何组件封装在临时组件中。

最好的方法是在启用了一些ES2015特性(即装饰器)的情况下使用ES2016转发器:

代码语言:javascript
复制
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这个主题的要点

票数 0
EN

Stack Overflow用户

发布于 2015-02-25 00:21:24

我想出了一个解决方案:

代码语言:javascript
复制
var RolesRequired = React.createClass({
    permitted: roles => ...,

    render: function () {
        if (!this.permitted(this.props.roles)) {
            return null;
        }

        return <div>{this.props.children}</div>;
    }
});

我正在做的是将被返回的子元素包装在一个<div>中,但是我必须添加一个不需要的/不需要的DOM元素来实现它。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28708936

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档