反应出口React.createContext未定义

时间:2019-05-05 12:47:34

标签: reactjs

我正在尝试学习React Context并陷入困境。需要帮助。

App.js

import React from 'react';
import Header from './components/Header';

export const MyContext = React.createContext("Default");

class App extends React.Component {
  render() {
    return (
      <MyContext.Provider value="dark">
        <Header />
      </MyContext.Provider>
    );
  }
}

export default App;

Header / index.js

import React, { Component } from 'react'
import { MyContext } from "./../../App";

class Header extends Component {
    //static contextType = MyContext;
    render() {
        return (
            <div>
                {this.context}
            </div>

        )
    }
}

Header.contextType = MyContext;
export default Header;

出现错误未定义MyContext 。 当我将Header类移至App.js时,它会起作用

我在做什么错? Tnx为您提供帮助

2 个答案:

答案 0 :(得分:0)

提供程序只为您保留值(有点像商店)。是消费者使它可用于您的组件。

Headerjs应该看起来像这样

// Header.js
import React, { Component } from 'react'
import { MyContext } from "./../../App";

class Header extends Component {
    //static contextType = MyContext;
    render() {
        return (
          <MyContext.Consumer>
            { value => {
              return <div>
                {value}
              </div>
            }}
         <MyContext.Consumer>
        )
    }
}

// Header.contextType = MyContext; not needed for react v16+
export default Header;

为了从Context中获得更多能量,我建议与高阶组件结合使用。例如,如果您想要的是主题系统 你可以做到的。

import React from "react";

const themes = {
  dark: {
    background: "#333"
  },
  light: {
    background: "#f5f5f9"
  }
};

const { Provider, Consumer } = React.createContext(themes);

export const ThemeProvider = ({ children }) => {
  return <Provider value={themes}>{children}</Provider>
};

export const withTheme = theme => {
  return Component => props => <Consumer>
      {themes => {
        return <Component {...props} style={{ ...themes[theme]}} />;
      }}
  </Consumer>
};

app.js

import Header from "./Header";
import { ThemeProvider } from './Theme'
class App extends React.Component {
  render() {
    return (
      <ThemeProvider>
        <Header />
      </ThemeProvider>
    );
  }
}

最后是 Header.js

import React, { Component } from "react";
import { withTheme } from "./Theme";

class Header extends Component {
  //static contextType = MyContext;
  render() {
    return <h1 style={{ ...this.props.style }}>Header</h1>;
  }
}

export default withTheme("dark")(Header);

您可以阅读 MY article on using context for auth for more

答案 1 :(得分:0)

两种方式可以使用上下文:

1。。通过使用上下文使用者:

 <MyContext.Consumer>
    { 
       contextValue => {
              return <div>
                {value}
              </div>
         }
     }
 <MyContext.Consumer>

2。。通过将上下文分配给对象:

static contextType = MyContext;
render(){
  const {value1,value2.......} = this.context
}

有关上下文的更多信息,请访问React官方页面。 https://reactjs.org/docs/context.html