Chr*_*sco 5 reactjs react-context
我正在使用返回包装组件的 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;
};
Run Code Online (Sandbox Code Playgroud)
但是,我制作了相同的代码,但使用<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;
};
Run Code Online (Sandbox Code Playgroud)
我在这里没有看到什么吗?
| 归档时间: |
|
| 查看次数: |
2652 次 |
| 最近记录: |