反应-类内的useContext

时间:2020-04-29 09:05:04

标签: reactjs react-native react-context use-context

我是React的新手,我想在我的课程中使用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)
  }
...
}

有人可以启发我吗?

1 个答案:

答案 0 :(得分:9)

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;
  }
}