簡體   English   中英

在react.js中創建一個未渲染的包裝器組件

[英]Creating a non-rendered wrapper component in react.js

我想創建一個進行安全檢查的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組件中返回所有RolesRequired

我想出了這個解決方案:

var RolesRequired = React.createClass({
    permitted: roles => ...,

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

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

我正在做的是將返回的孩子包裝在<div>但是我必須添加一個不需要的/不需要的DOM元素來實現它。

我認為高階分量(HOC)也是一個不錯的選擇。 你基本上可以包裝在HOC定義一些行為,並決定是否應該呈現wrappe任何部件。

最好的方法是使用啟用了某些ES2016功能(即裝飾器)的ES2015轉譯器:

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功能,是因為我認為更好地理解這一點,但是您可以通過簡單的函數包裝來實現這一點,這是React核心成員之一關於HOC的要旨https:// gist。 github.com/sebmarkbage/ef0bf1f338a7182b6775

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM