无法获取`contextType`属性以用于React Context API

时间:2018-11-20 14:22:20

标签: javascript reactjs react-context

我在获取作为新React Context API一部分的React contextType属性时遇到麻烦。文件说:

  

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

除非我错过了任何事情,否则以下代码应使this.context类上的App可用:

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

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

有人可以帮助我了解这里的情况吗?

1 个答案:

答案 0 :(得分:2)

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