React - 新上下文 API 不适用于 Class.contextType,但适用于 Context.Consumer

React - New Context API not working with Class.contextType, but works with Context.Consumer

我正在使用 returns 包装组件的 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;
};

我这里没看到什么吗?

事实证明,即使我将我的反应脚本更新为 2.0,我也必须自己将反应更新为 16.6(之前在 16.3 上)。

我的印象是 react-scripts 也会处理 react 版本。不好意思,弄糊涂了。