【发布时间】:2019-04-23 00:28:10
【问题描述】:
我无法获取作为新 React Context API 一部分的 React contextType 属性。文件说:
可以为类的 contextType 属性分配一个由 React.createContext() 创建的 Context 对象。这使您可以使用 this.context 使用该上下文类型的最接近的当前值。您可以在包括渲染函数在内的任何生命周期方法中引用它。
除非我遗漏了什么,否则下面的代码应该使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)
但是,当这段代码运行时,日志语句只打印一个空对象。我希望它能打印出我提供给React.createContext 函数的默认状态。
谁能帮我理解这里发生了什么?
【问题讨论】:
标签: javascript reactjs react-context