【问题标题】:Trouble getting `contextType` property to work for React Context API无法让 `contextType` 属性适用于 React Context API
【发布时间】:2019-04-23 00:28:10
【问题描述】:

我无法获取作为新 React Context API 一部分的 React contextType 属性。文件说:

可以为类的 contextType 属性分配一个由 React.createContext() 创建的 Context 对象。这使您可以使用 this.context 使用该上下文类型的最接近的当前值。您可以在包括渲染函数在内的任何生命周期方法中引用它。

除非我遗漏了什么,否则下面的代码应该使this.contextApp 类中可用:

import React from "react";
import ReactDOM from "react-dom";

const MyContext = React.createContext({
  on: false
});

import "./styles.css";

class App extends React.Component {
  render() {
    console.log("context: ", this.context);
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
      </div>
    );
  }
}
App.contextType = MyContext;

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

(例如here

但是,当这段代码运行时,日志语句只打印一个空对象。我希望它能打印出我提供给React.createContext 函数的默认状态。

谁能帮我理解这里发生了什么?

【问题讨论】:

    标签: javascript reactjs react-context


    【解决方案1】:

    我认为您需要 React &gt;=16.6.0 才能使用此功能。 我在你的代码框中更新了 react,它对我有用:https://codesandbox.io/s/w66k2k8o5l

    【讨论】:

    • 我正在反应 16.8.6 但我遇到了同样的问题。
    • 仔细阅读,当存在循环依赖时,也会出现问题。但对我来说不是这样。
    猜你喜欢
    • 1970-01-01
    • 2019-04-06
    • 2021-05-05
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 2021-07-18
    相关资源
    最近更新 更多