我很难做出反应
contextType
属性,它是新的React上下文API的一部分。文件上说:
可以为类的ContextType属性分配由React.CreateContext()创建的上下文对象。这允许您使用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
)
但是,当该代码运行时,LOG语句只打印一个空对象。我希望它打印出我提供给
React.createContext
功能。
有人能帮我弄明白这是怎么回事吗?