【问题标题】:React context how it works反应上下文它是如何工作的
【发布时间】:2020-05-05 04:39:30
【问题描述】:

学习 React 并想知道以下使用上下文的方式在幕后是如何工作的?

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

this.context 如何通过声明static contextType 自动设置?

【问题讨论】:

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

标签: reactjs react-context


【解决方案1】:

可以在此处找到处理此问题的代码:https://github.com/facebook/react/blob/master/packages/react-reconciler/src/ReactFiberClassComponent.new.js#L531

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

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

【讨论】:

  • 如果它是一个功能组件?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-04
  • 1970-01-01
  • 2013-09-27
  • 2022-07-18
  • 2015-05-06
相关资源
最近更新 更多