gpt4 book ai didi

javascript - 无法使 `contextType` 属性用于 React Context API

转载 作者:行者123 更新时间:2023-11-30 11:11:39 27 4
gpt4 key购买 nike

我在获取作为新 React Context 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 类上可用:

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

关于javascript - 无法使 `contextType` 属性用于 React Context API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53395075/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com