React - 新的 Context API 不适用于 Class.contextType,但适用于 Context.Consumer

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)

我在这里没有看到什么吗?

Chr*_*sco 6

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

我的印象是反应脚本也可以处理反应版本。我的错,在那里感到困惑。