React - 类内的 useContext

Han*_* Nr 11 reactjs react-native react-context use-context

我是 React 新手,我想在我的班级中使用 useContext,我该如何解决这个问题?这是我当前代码的示例

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

const ChatList = ({ onAction }) => {
    const {state, fetchChatList} = useContext(Context)
Run Code Online (Sandbox Code Playgroud)

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

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)
  }
...
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以启发我吗?

Shu*_*tri 27

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果我们必须使用多个上下文怎么办? (7认同)
  • @CarlosCarucce [此处](/sf/answers/3779215121/)有一个解决方法。 (2认同)
  • 对于多个上下文,请参阅 https://reactjs.org/docs/context.html#consuming-multiple-contexts (2认同)