何时调用' React.createClass({})() ' ?

When is `React.createClass({})()` called

本文关键字:React 调用 何时 createClass      更新时间:2023-09-26

我正在挖掘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({})时,您得到Constructor函数,该函数有两个参数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抽象地),你的类被绑定到React.createElement作为type,与绑定函数得到返回(见这里)。
  • 这个绑定函数就是当你用(或不带)props调用你的类时实际被调用的。
  • 当它作为node传递给render时,render方法(上面的链接)将element变量设置为node参数,然后直接实例化它或将其传递给其他库进行实例化。