14

我是新手,我想在课堂上使用 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)
  }
...
}

任何人都可以启发我吗?

4

2 回答 2

31

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;
  }
}
于 2020-04-29T09:08:16.737 回答
2

可以为类的 contextType 属性分配一个由 React.createContext() 创建的 Context 对象。

注意我们如何在类之外将 MyContext 的值分配给Class.contextType

然后,您可以使用this.context

import MyContext from '@/context/MyContext'

class Login extends React.component() {

  constructor(props) {
    super(props);

    this.state = { four: 2*2 }
  }

  render() {

    console.log(this.context);
    
    return (
      <div>

      </div>
    )
  }

}

Login.contextType = MyContext
于 2021-09-16T17:39:36.907 回答