[英]How to use React Context inside function of Class component
How can I access objects inside of React Context inside a function of a Class Component.如何在类组件的函数内访问 React Context 内的对象。
I've got the following React Component我有以下 React 组件
import StoreContext from '../../context/StoreContext'
class ProductForm extends Component {
static contextType = StoreContext
constructor(props) {
super(props);
}
handleOptionChange(event) {
const test = this.contextType.client.testObject
}
I've tried accessing the client
object inside the context like this but It doesn't work because it says cant read the property of undefined.我试过像这样访问上下文中的
client
对象,但它不起作用,因为它说无法读取未定义的属性。
I'm wondering where my mistake is.我想知道我的错误在哪里。
Change this to context instead of contextType将此更改为 context 而不是 contextType
this.context.client.testObject
ie Your code should look like即你的代码应该看起来像
import StoreContext from '../../context/StoreContext'
class ProductForm extends Component {
static contextType = StoreContext
constructor(props) {
super(props);
}
handleOptionChange(event) {
const test = this.context.client.testObject
}
Leave the static propery as context type and access context in methods as using this.context将静态属性保留为上下文类型,并在使用 this.context 的方法中访问上下文
I would describe using context in a class component in 3 steps我将分 3 个步骤描述在类组件中使用上下文
define the context object with a value you want to share with entire app使用要与整个应用程序共享的值定义上下文对象
const StaticBackEditor = React.createContext({isDebug: true})
wrap the entire app this context and set the values将此上下文包装整个应用程序并设置值
function App() {
return (
<Provider store={store}>
<StaticBackEditor.Provider value={{isDebug: true}}>
<div className="App">
<Layout />
</div>
</StaticBackEditor.Provider>
</Provider>
)
use the value in a component使用组件中的值
class Tree extends React.Component<IProps, IState> {
// this must be named contextType!
static contextType = StaticBackEditor
}
// its wired that we need to access a static field through this , but you do!
{this.context.isDebug && <span className="debug">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.