无法让 `contextType` 属性 为 React Context API 工作

Trouble getting `contextType` property to work for React Context API

我在获取作为新 React 上下文 API 一部分的 React contextType 属性 时遇到问题。文件说:

The contextType property on a class can be assigned a Context object created by React.createContext(). This lets you consume the nearest current value of that Context type using this.context. You can reference this in any of the lifecycle methods including the render function.

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

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 函数的默认状态。

谁能帮我理解这是怎么回事?

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