React styled-components theme-provider 动态主题

React styled-components theme-provider dynamic theme

我正在尝试在我的 React 应用程序中实现深色和浅色主题。我知道主题是如何工作的,所以我正在像下面这样配置我的按钮,例如:

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

然后我将主题定义为常量:

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

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

当我想在某个地方使用主题时,我会这样做:

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

但我想要实现的是动态更改主题(可能是在按钮上的单击功能上)。我是 React 的新手,所以请不要对我刻薄。

是这样的吗? 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'));