2015-06-04 23 views
0

我正在挖掘React.js來源,這是我目前正在嘗試瞭解。什麼時候是`React.createClass({})()`調用

var ReactClass = { 
    /* 
    * @param {object} spec Class specification (which must define `render`). 
    * @return {function} Component constructor function. 
    * @public 
    */ 
    createClass: function(spec) { 
     var Constructor = function(props, context) { 
      // ... 
      this.props = props; 
      this.context = context; 
      this.state = null; 

      // ReactClasses doesn't have constructors. Instead, they use the 
      // getInitialState and componentWillMount methods for initialization. 
      var initialState = this.getInitialState ? this.getInitialState() : null; 
      // ... 
      this.state = initialState; 
     }; 

     Constructor.prototype = new ReactClassComponent(); 
     Constructor.prototype.constructor = Constructor; 
     // ... 
     mixSpecIntoComponent(Constructor, spec); 
     // ... 
     return Constructor; // <--- Who calls this? 
    }, 
    // ... 
}; 

當調用React.createClass({})你得到Constructor函數有兩個參數props, context

這個函數/方法叫做什麼,I.e.誰在做實際的React.createClass({})(someProps, someContext)

+1

好,只要你* *實例化一個'新MyReactClass'它被稱爲'無功研究所=新的組件(publicProps,publicContext)之外 – Bergi

+0

@Bergi;'我只是不能在源代碼任意找到它。 .. –

+0

你在找哪個來源?我希望這些用戶定製的類可以從應用程序代碼中調用,而不是從庫代碼中調用。 – Bergi

回答

2

這並不簡單,你是對的。

簡短的回答是ConstructorReact.render調用。

看到這裏的實際實例塊:https://github.com/facebook/react/blob/4c3e9650ba6c9ea90956a08542d9fa9b5d72ee88/src/renderers/shared/reconciler/instantiateReactComponent.js#L75

的基本路徑是這樣的:

  • 您創建一個ReactClass,其中有Constructor返回值。
  • 當您創建工廠(直接使用React.createFactory或通過JSX抽象化)時,您的類將被綁定到React.createElement,作爲type,返回綁定函數(請參閱here)。
  • 這個綁定函數是當你調用帶有(或不帶)道具的類時真正調用的函數。
  • 當該被傳遞到作爲rendernode,所述render方法(上面鏈接)設置一個element變量到node參數,然後直接實例化,或將其傳遞給其他的庫來實例化。
+0

我希望我可以不止一次地對此讚賞!很好的答案。 –

相關問題