【发布时间】:2019-04-06 04:47:05
【问题描述】:
我正在尝试使用返回包装组件的 HOC 的新上下文 API。当我使用Class.contextType = Context 方法时它不起作用:
return function myHOC(WrappedComponent) {
class HOC extends React.Component {
// static contextType = MyContext;
render() {
console.log(this.context); // HERE, this logs `{}`
// ..do stuff
return <WrappedComponent {...this.props} />
}
}
HOC.contextType = MyContext;
return HOC;
};
但是,我编写了相同的代码,但使用了<MyContext.Consumer>,它运行良好:
return function myHOC(WrappedComponent) {
const HOC = (props) => (
<MyContext.Consumer>
{(context) => {
console.log(context); // HERE, correct values
return <WrappedComponent {...props} />
}}
</MyContext.Consumer>
);
return HOC;
};
我在这里没有看到什么吗?
【问题讨论】:
-
对于像我这样正在寻找被重定向到这个问题的 Class.contextType 和 Context.Consumer 之间的区别的其他人,这是一个答案:stackoverflow.com/questions/54283509/…
标签: reactjs react-context