React-新的上下文API不适用于Class.contextType,但可以与Context.Consumer一起使用

时间:2018-11-01 22:13:54

标签: 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;
};

但是,我使用<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;
};

我在这里没看到东西吗?

1 个答案:

答案 0 :(得分:4)

事实证明,即使我将自己的react-scripts更新为2.0,我也必须自己更新对16.6(以前是16.3)的reacts。

我的印象是react-scripts也可以处理react版本。我不好,在那里感到困惑。