gpt4 book ai didi

javascript - `React.createClass({})()`何时被调用

转载 作者:行者123 更新时间:2023-12-02 16:06:41 24 4
gpt4 key购买 nike

我正在挖掘 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({}) 时,您将获得带有两个参数 props, contextConstructor 函数。

这个函数/方法在哪里调用,即谁执行实际的 React.createClass({})(someProps, someContext)

最佳答案

这并不简单,你是对的。

简短的回答是 ConstructorReact.render 调用。

请参阅此处了解实际的实例化 block :https://github.com/facebook/react/blob/4c3e9650ba6c9ea90956a08542d9fa9b5d72ee88/src/renderers/shared/reconciler/instantiateReactComponent.js#L75

基本路径是这样的:

  • 您创建一个 ReactClass,其返回值为 Constructor
  • 当您创建工厂时(直接使用 React.createFactory 或通过 JSX 抽象地创建),您的类将作为 type 绑定(bind)到 React.createElement code>,返回绑定(bind)函数(参见 here )。
  • 当您使用(或不使用) Prop 调用类时,实际上会调用这个绑定(bind)函数。
  • 当它作为 node 传递给 render 时,render 方法(上面链接)会设置一个 element变量传递给 node 参数,然后直接实例化它或将其传递给其他库来实例化。

关于javascript - `React.createClass({})()`何时被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30652616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com