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



我正在实现一个暗模式主题来理解 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;

ThemeContextProvider中初始化之前使用该值ThemeContext值。

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>
);
};

相关内容

  • 没有找到相关文章

最新更新