React 中 context 的使用

引自我的博客 [走啊走的記錄] - React 中 context 的使用javascript

官方文檔說明(英)html

看了別人寫的中文博客,再看了官方英文文檔,發現仍是官方文檔講的淺顯易懂一些,看了以後,半翻譯半理解地寫了這篇博客,更易於新手理解。java

介紹

context 是在 react @ 0.14 版本之後發佈的一個高級且實驗性的功能,有可能在將來作出更改。不推薦頻繁使用,若是使用的話儘可能保持在小範圍內而且避免直接使用 context 的 API,爲了之後升級框架更加容易。react

使用 Context 的緣由

爲了有時候想傳遞數據經過組件樹,可是不想給每一層級的組件手動傳遞屬性,那麼 context 就能幫你 "越級" 傳遞數據到組件樹中你想傳遞到的深層次組件。git

有時候 A組件 爲了給 B組件 中的 C組件 傳遞一個 prop ,而須要把參數在組件中傳遞兩次才能最終將 A組件 中的 prop 傳遞給 C組件github

官方文檔的示例代碼以下框架

var Button = React.createClass({
  render: function() {
    return (
      <button style={{background: this.props.color}}>
        {this.props.children}
      </button>
    );
  }
});

var Message = React.createClass({
  render: function() {
    return (
      <div>
        {this.props.text} <Button color={this.props.color}>Delete</Button>
      </div>
    );
  }
});

var MessageList = React.createClass({
  render: function() {
    var color = "purple";
    var children = this.props.messages.map(function(message) {
      return <Message text={message.text} color={color} />;
    });
    return <div>{children}</div>;
  }
});

使用 context 改進數據傳遞

如今咱們使用 context 來完成參數的傳遞試試this

var Button = React.createClass({
  // 必須指定context的數據類型
  contextTypes: {
    color: React.PropTypes.string
  },
  render: function() {
    return (
      <button style={{background: this.context.color}}>
        {this.props.children}
      </button>
    );
  }
});

var Message = React.createClass({
  render: function() {
    return (
      <div>
        {this.props.text} <Button>Delete</Button>
      </div>
    );
  }
});

var MessageList = React.createClass({
  //
  childContextTypes: {
    color: React.PropTypes.string
  },
  getChildContext: function() {
    return {color: "purple"};
  },
  render: function() {
    var children = this.props.messages.map(function(message) {
      return <Message text={message.text} />;
    });
    return <div>{children}</div>;
  }
});

示例代碼中經過添加 childContextTypesgetChildContext()MessageListcontext 的提供者),React 自動向下傳遞數據而後在組件樹中的任意組件(也就是說任意子組件,在此示例代碼中也就是 Button)都能經過定義 contextTypes 訪問 context 中的數據。翻譯

總結

指定數據並要將數據傳遞下去的父組件要定義 childContextTypesgetChildContext();想要接收到數據的子組件 必須定義 contextTypes 來使用傳遞過來的 contextcode

相關文章
相關標籤/搜索