首页 > 解决方案 > React - 类内的useContext

问题描述

我是新手,我想在课堂上使用 useContext,我该如何解决?这是我当前代码的示例

import { Context } from '../context/ChatListContext'

const ChatList = ({ onAction }) => {
    const {state, fetchChatList} = useContext(Context)

我对我的班级也有同样的期待

import { Context } from '../context/ChatListContext'

class MainScreen extends Component {

//const {state, fetchChatList} = useContext(Context) *how do i declare this?

  constructor(props) {
    super(props)
    this.state = { loading: true, showAction: false }
    setTimeout(() => {
      StatusBar.setBackgroundColor(primary)
    }, 100)
  }
...
}

任何人都可以启发我吗?

标签: reactjsreact-nativereact-contextuse-context

解决方案


useContext是一个不能在类组件中使用的钩子。对于一个类组件,您定义一个static contextType

import { Context } from '../context/ChatListContext'

class MainScreen extends Component {

 static contextType = Context

  constructor(props) {
    super(props)
    this.state = { loading: true, showAction: false }
    setTimeout(() => {
      StatusBar.setBackgroundColor(primary)
    }, 100)
  }
...
  render() {
       const {state, fetchChatList} =this.context;
  }
}

推荐阅读