如何在 Class 组件的函数内使用 React Context [英] How to use React Context inside function of Class component

查看:51
本文介绍了如何在 Class 组件的函数内使用 React Context的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在类组件的函数内访问 React Context 内的对象.

How can I access objects inside of React Context inside a function of a Class Component.

我有以下 React 组件

I've got the following React Component

import StoreContext from '../../context/StoreContext'

class ProductForm extends Component {
  static contextType = StoreContext

  constructor(props) {
    super(props);

  }

  handleOptionChange(event) {

    const test = this.contextType.client.testObject

  }

我已经尝试像这样访问上下文中的 client 对象,但它不起作用,因为它说无法读取未定义的属性.

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.

我想知道我的错误在哪里.

I'm wondering where my mistake is.

推荐答案

将此更改为 context 而不是 contextType

Change this to context instead of contextType

this.context.client.testObject

即你的代码应该看起来像

i.e 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

  }

将静态属性保留为上下文类型并在方法中使用 this.context 访问上下文

Leave the static propery as context type and access context in methods as using this.context

这篇关于如何在 Class 组件的函数内使用 React Context的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆