【问题标题】:React styled-components theme-provider dynamic themeReact styled-components theme-provider 动态主题
【发布时间】:2018-02-09 00:02:52
【问题描述】:

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

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

然后我将主题定义为 consts:

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 的新手,所以请不要对我刻薄。

【问题讨论】:

    标签: javascript reactjs themes state styled-components


    【解决方案1】:

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

    【讨论】:

    猜你喜欢
    • 2018-10-20
    • 2018-08-17
    • 2021-04-06
    • 1970-01-01
    • 2020-02-13
    • 2019-03-03
    • 2021-11-04
    • 2020-12-19
    • 2019-10-07
    相关资源
    最近更新 更多