简体   繁体   English

我怎样才能在反应中保存黑暗模式state

[英]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.

相关问题 如何保存 cookies 以进行暗模式和亮模式切换? - How can I save cookies for dark mode and light mode toggling? 如何在浏览器中保存暗模式值(使用jquery) - How can i save the dark mode value in browsers ( using jquery ) React Native - 类型脚本:即使在关闭应用程序后,如何保存暗模式切换 state? - React Native - Type Script: How to save dark mode toggle state even after turning off the application? 如何在本机应用程序中实现暗模式 - How can I implement dark mode in react native app React:我怎样才能为明暗模式动态更改整个背景? Redux 持有我的黑暗模式 state - React: How can I dynamically change the entire background dynamically for light and dark mode? Redux holds my darkMode state 如何更改 state 以使我的切换按钮更改为暗模式? - How can i change the state for my toggle button to change to dark mode? 如何使用 localStorage 使浏览器记住亮/暗模式主题切换的类列表切换状态? - How can I use localStorage to make the browser remember a classlist toggle state for a light/dark mode theme switch? 如何为暗/亮模式切换保存 cookie? - How to save cookies for Dark/Light Mode Toggle? 如何在 JavaScript 中将暗模式保存到本地存储 - How to save Dark mode to local storage in JavaScript 如何在深色模式下显示浅色徽标? - How can I show light logo in dark mode?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM