添加暗模式但上下文未定义
Posted
技术标签:
【中文标题】添加暗模式但上下文未定义【英文标题】:Adding dark mode but context is undefined 【发布时间】:2020-05-12 03:15:07 【问题描述】:我正在实现一个暗模式主题来理解 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】:您在 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>
);
;
【讨论】:
以上是关于添加暗模式但上下文未定义的主要内容,如果未能解决你的问题,请参考以下文章