簡體   English   中英

什么時候調用`React.createClass({})()`

[英]When is `React.createClass({})()` called

我正在研究React.js源代碼,這就是我當前想要了解的內容。

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({})您將獲得React.createClass({})兩個參數props, contextConstructor函數props, context

該函數/方法在哪里調用,即實際的React.createClass({})(someProps, someContext)誰?

這並不簡單,你是對的。

簡短的答案是ConstructorReact.render

此處查看實際的實例化塊: https : //github.com/facebook/react/blob/4c3e9650ba6c9ea90956a08542d9fa9b5d72ee88/src/renderers/shared/reconciler/instantiateReactComponent.js#L75

基本路徑是這樣的:

  • 您創建一個ReactClass ,其返回值為Constructor
  • 當創建工廠時(直接使用React.createFactory或抽象地通過JSX),您的類將作為type綁定到React.createElement ,並且返回綁定的函數(請參見此處 )。
  • 當您使用(或不使用)道具調用類時,實際上會調用此綁定函數。
  • 當將其傳遞給render作為noderender方法(上面鏈接)將element變量設置為node參數,然后直接實例化該變量,或將其傳遞給其他lib進行實例化。

暫無
暫無

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

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