[英]how can i save the dark mode state in react
I am wondering how I can save the state of dark mode in my components so I can use it without getting the initialized value over and over again when i navigate different pages.我想知道如何在我的组件中保存暗模式的 state,这样我就可以使用它而无需在浏览不同页面时一遍又一遍地获取初始化值。 this is the code:这是代码:
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = { isDark: false }
this.handleOnClick = this.handleOnClick.bind(this);
}
handleOnClick = () => {
this.setState(prevState => ({ isDark: !prevState.isDark }))
}
componentDidUpdate() {
if (this.state.isDark === true) {
setTheme('theme-dark');
} else setTheme('theme-light');
}
I would go take a look at React Context, themeing is a prime use case for it https://reactjs.org/docs/context.html#dynamic-context我会 go 看看 React Context,主题是它的主要用例https://reactjs.org/docs/context.html#dynamic-context
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.