如何在 Class 组件的函数中使用 React Context

IT技术 javascript reactjs
2021-05-23 19:03:28

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

我有以下 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

  }

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

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

2个回答

将此更改为 context 而不是 contextType

this.context.client.testObject

即你的代码应该看起来像

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 的方法中访问上下文

我将分 3 个步骤描述在类组件中使用上下文

使用要与整个应用程序共享的值定义上下文对象

const StaticBackEditor = React.createContext({isDebug: true})

将此上下文包装整个应用程序并设置值

function App() {
    return (
        <Provider store={store}>
            <StaticBackEditor.Provider value={{isDebug: true}}>
                <div className="App">
              <Layout />
        </div>
                </StaticBackEditor.Provider>
            </Provider>
        )

使用组件中的值

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">