React - 类内的 useContext [英] React - useContext inside class
本文介绍了React - 类内的 useContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 React 新手,我想在我的班级中使用 useContext,我该如何解决这个问题?这是我当前代码的示例
I'm newbie in react and i want use useContext inside my class, how do i solve this? This is example of my current code right now
import { Context } from '../context/ChatListContext'
const ChatList = ({ onAction }) => {
const {state, fetchChatList} = useContext(Context)
我对我的班级也有同样的期待
And i'm expecting the same for my class
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)
}
...
}
有人能指教我吗?
推荐答案
useContext
是一个无法在类组件中使用的钩子.对于类组件,您定义一个 static contextType
useContext
is a hook that can't be used in a class component. For a class component you define a 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;
}
}
这篇关于React - 类内的 useContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文