Reactjs 对其工作原理作出反应

Reactjs 对其工作原理作出反应,reactjs,context-api,Reactjs,Context Api,学习如何反应,并好奇地想知道下面的消费语境的方式在幕后是如何运作的 static contextType = MyContext; render() { let value = this.context; /* render something based on the value */ } } this.context是如何通过声明静态contextType自动设置的?处理此问题的代码可以在此处找到: 简而言之,它们检查ctor.contextType是否存在(其

学习如何反应,并好奇地想知道下面的消费语境的方式在幕后是如何运作的

  static contextType = MyContext;
  render() {
    let value = this.context;
    /* render something based on the value */
  }
}

this.context
是如何通过声明
静态contextType
自动设置的?

处理此问题的代码可以在此处找到:

简而言之,它们检查
ctor.contextType
是否存在(其中
ctor
是组件的构造函数)。如果有,他们读取上下文中的值,然后用该值调用构造函数

const contextType = ctor.contextType;
//...
if (typeof contextType === 'object' && contextType !== null) {
    context = readContext((contextType: any));
}
//...
const instance = new ctor(props, context);

如果在类上指定静态属性,例如
App
,react可以使用
App.contextType
访问该属性,并将上下文值作为道具提供