代码之家  ›  专栏  ›  技术社区  ›  fraxture

无法使“contexttype”属性用于react context api

  •  1
  • fraxture  · 技术社区  · 6 年前

    我很难做出反应 contextType 属性,它是新的React上下文API的一部分。文件上说:

    可以为类的ContextType属性分配由React.CreateContext()创建的上下文对象。这允许您使用this.context使用该上下文类型最近的当前值。您可以在包括渲染函数在内的任何生命周期方法中引用它。

    除非我漏掉了什么,否则下面的代码应该 this.context 在上提供 App 班级:

    import React from "react";
    import ReactDOM from "react-dom";
    
    const MyContext = React.createContext({
      on: false
    });
    
    import "./styles.css";
    
    class App extends React.Component {
      render() {
        console.log("context: ", this.context);
        return (
          <div className="App">
            <h1>Hello CodeSandbox</h1>
            <h2>Start editing to see some magic happen!</h2>
          </div>
        );
      }
    }
    App.contextType = MyContext;
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
    

    (例) here )

    但是,当该代码运行时,LOG语句只打印一个空对象。我希望它打印出我提供给 React.createContext 功能。

    有人能帮我弄明白这是怎么回事吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Johannes Reuter    6 年前

    我想你需要 React >=16.6.0 对于此功能。 我在你的代码沙盒中更新了react,它对我很有用: https://codesandbox.io/s/w66k2k8o5l