添加暗模式但上下文未定义

时间:2020-01-26 14:43:08

标签: javascript reactjs react-hooks react-context

我正在实现黑暗模式主题以了解React上下文。我的标题组件具有相同的代码,并且工作正常。当我尝试为主标签添加相同内容时,出现类型错误:_useContext未定义。

import React, { useContext } from 'react';
import Heading from './heading/heading';
import ThemeToggle from './heading/themeToggle';
import ThemeContextProvider from './context/ThemeContex';
import './App.css';
import { ThemeContext } from './context/ThemeContex';

const App = () => {
  const { light, dark, isLightTheme } = useContext(ThemeContext);
  const theme = isLightTheme ? light : dark;

  return (
    <>
      <ThemeContextProvider>
        <div className="grid">
          <>
            <Heading />
            <ThemeToggle />
          </>
          <main style={{ background: theme.bh, color: theme.color }}>
            <div className="first-container">
              <img src={require('./img/madeInAbyss.jpeg')} />
            </div>
            <div className="second-container"></div>
          </main>
        </div>
      </ThemeContextProvider>
    </>
  );
};

export default App;

这是上下文提供程序文件,它只有一个颜色主题对象和一个在暗和亮模式之间切换的状态

import React, { createContext, useState } from 'react';

export const ThemeContext = createContext();

const ThemeContextProvider = props => {
  const [isLightTheme, setIsLightTheme] = useState(true);

  const colorTheme = {
    light: { ui: '#ddd', bg: '#eee' },
    dark: { color: '#fff', bg: '#15202b' }
  };
  console.log(colorTheme);

  const toggleTheme = () => {
    setIsLightTheme(!isLightTheme);
  };

  return (
    <ThemeContext.Provider
      value={{
        ...colorTheme,
        isLightTheme: isLightTheme,
        toggleTheme: toggleTheme
      }}>
      {props.children}
    </ThemeContext.Provider>
  );
};

export default ThemeContextProvider;

1 个答案:

答案 0 :(得分:1)

您使用ThemeContext值,然后在ThemeContextProvider中对其进行初始化。

const App = () => {
  // ThemeContext initial value is undefined (createContext())
  // will throw a runtime error
  const { light, dark, isLightTheme } = useContext(ThemeContext);

  return (
    <ThemeContextProvider>
      {/* ThemeContext initialized only on ThemeContextProvider render */}
      {/* after .Provider value is supplied */}
    </ThemeContextProvider>
  );
};

要修复此问题,请提供一个初始值:

// Should be in an outer scope.
const colorTheme = {
  light: { ui: '#ddd', bg: '#eee' },
  dark: { color: '#fff', bg: '#15202b' },
  isLightTheme: true,
};

export const ThemeContext = createContext(colorTheme);

const ThemeContextProvider = props => {
  ...

  return (
    <ThemeContext.Provider
      value={...}>
      {props.children}
    </ThemeContext.Provider>
  );
};