简体   繁体   中英

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM