我在获取作为新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
函数的默认状态。
有人可以帮助我了解这里的情况吗?
答案 0 :(得分:2)
我认为您需要React >=16.6.0
才能使用此功能。
我更新了您的codeandbox中的react,它对我有用:https://codesandbox.io/s/w66k2k8o5l