简体   繁体   中英

React styled-components theme-provider dynamic theme

I'm trying to achieve dark and light themes in my React app. I know how themes work, so I'm configuring my button like below, for example :

const Button = styled.button`
   /* some styles */
    color: ${props => props.theme.main}
`;

Then I'm defining themes as consts:

const dark = {
    main: 'black',
    text: 'switch to light mode'
};

const light = {
    main: 'white',
    text: 'switch to dark mode'
};

And when I want to use the theme somewhere I do it like this:

  <ThemeProvider theme={dark}>
    <Button>{dark.text}</Button>
  </ThemeProvider>

But what I want to achieve is to change the theme dynamically (on a click function on the button probably). I'm kind of new to React so please don't be mean to me.

Something like this? Demo

import React, { Component } from 'react';
import { render } from 'react-dom';
import styled, { ThemeProvider } from 'styled-components';

const themes = {
  'light': {
    main: '#EFEFEF',
  },
  'dark': {
    main: '#666',
  }
}

const DynamicDiv = styled.div`
  background: ${({ theme }) => theme.main};
`

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      theme: themes['light']
    };
  }

  handleDark = () => {
    this.setState({ theme: themes['dark'] })
  }

  render() {
    return (
      <ThemeProvider theme={this.state.theme}>
        <div>
          <DynamicDiv>{this.state.name}</DynamicDiv>
          <div onClick={this.handleDark}>Change to Dark</div>
        </div>
      </ThemeProvider>
    );
  }
}

render(<App />, document.getElementById('root'));

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