【问题标题】:React - useContext inside classReact - 类内的useContext
【发布时间】:2020-08-13 07:39:46
【问题描述】:

我是 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)
  }
...
}

谁能赐教?

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    【解决方案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-11
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 2022-08-07
      相关资源
      最近更新 更多