您好,我想通过自定义钩子寻求帮助 我无法以仅将主题放在单个文件中的方式构建
我需要在主题和组件中导入主题 我已经尝试了所有方法,但无法解决,基本上我需要将主题首选项保存在本地存储中,默认主题是浅色
代码:
import { darkTheme, lightTheme } from './themes/index';
export default function App() {
const [theme, setTheme] = usePersistedState('theme');
const toggleTheme = () => {
setTheme(theme.type === 'light' ? darkTheme : lightTheme);
};
return (
<ThemeProvider theme={theme}>
<GlobalStyle />
<div className="App">
<button onClick={toggleTheme}>a</button>
</div>
</ThemeProvider>
);
我的钩子:
function usePersistedState(key) {
const [state, setState] = useState(() => {
const storageValue = JSON.parse(localStorage.getItem(key));
console.log(storageValue);
switch (storageValue) {
case 'dark':
return darkTheme;
case 'light':
return lightTheme;
default:
return lightTheme;
}
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(state.type));
}, [key, state]);
return [state, setState];
}