我在github上的网站在所有浏览器上都能正常运行,直到我添加了切换主题功能。现在,它在野生动物园上呈现了一个空白页。但是,如果您从ios上的Messenger上打开网站链接,则可以正常显示。
这些是我添加切换功能的方式
// useDarkMode.js
import { useEffect, useState } from 'react';
import { blueTheme, darkTheme } from '../../theme';
export const useDarkMode = () => {
const [theme, setTheme] = useState('dark');
const [componentMounted, setComponentMounted] = useState(false);
const setMode = mode => {
window.localStorage.setItem('theme', mode)
setTheme(mode)
};
const toggleTheme = () => {
if (theme === 'light') {
setMode('dark')
} else {
setMode('light')
}
};
useEffect(() => {
const localTheme = window.localStorage.getItem('theme');
console.log(localTheme);
window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches && !localTheme ?
setMode('dark') :
localTheme ?
setTheme(localTheme) :
setMode('light');
setComponentMounted(true);
}, []);
return [theme, toggleTheme, componentMounted]
};
const Toggle = ({ theme, toggleTheme }) => {
const isLight = theme === 'light';
return (
<ToggleContainer onClick={toggleTheme} >
<SunIcon />
<MoonIcon />
</ToggleContainer>
);
};
Toggle.propTypes = {
theme: string.isRequired,
toggleTheme: func.isRequired,
}
export default Toggle;
function App() {
console.log("starting");
const [theme, toggleTheme, componentMounted] = useDarkMode();
const themeMode = theme === 'light' ? blueTheme : darkTheme;
console.log(themeMode);
if (!componentMounted) {
return <div />
};
return (
<ThemeProvider theme={themeMode}>
<>
<GlobalStyles />
<div>
<Main theme={themeMode} />
</div>
<Toggle theme={theme} toggleTheme={toggleTheme} />
<Footer theme={themeMode} />
</>
</ThemeProvider>
);
}