作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 React
上下文新 API,如下代码所示。最后一行将把上下文注册到我的组件中。我想知道如何将 contextType
用于无状态组件?
class MyClass extends React.Component {
render() {
let value = this.context;
/* render something based on the value of MyContext */
}
}
MyClass.contextType = MyContext;
我尝试了下面的代码,但它似乎不起作用。组件中的上下文
是空对象。
const MyClass = (props, context) => {
...
}
MyClass.contextType = MyContext;
最佳答案
没有办法用 contextType 来做到这一点。
您应该将 contextConsumer 与 renderProps 模式或 React 的 useContext Hook (在 React 16.8 中引入)结合使用
第一个看起来像这样:
const MyClass = (props) => {
return (
<myContext.Consumer>
{({name}) => <View>{name}</View>}
</myContext.Consumer>
)
}
第二种(首选)方法如下所示:
import React, {useContext} from 'react';
const MyClass = (props) => {
const {name} = useContext(myContext)
return <View>{name}</View>
}
关于reactjs - 如何在无状态组件上设置 `contextType`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54721441/
我是一名优秀的程序员,十分优秀!