【问题标题】:React Dynamic Themes反应动态主题
【发布时间】:2021-01-21 17:21:24
【问题描述】:

我有一个 React 16 应用程序,并希望允许用户通过按一个按钮来更改整个应用程序(包括所有路由)的主题。

例如,我可以在 SCSS 中有两个主题:

.theme-1 {
    background-color: $bg-color-1;
    color: $color-1;
}
.theme-2 {
    background-color: $bg-color-2;
    color: $color-2;
}

然后我会有一个如下的按钮:

<Button onClick={ this.changeTheme() }

这可以吗?具体来说,我想弄清楚这两个部分:

  1. 如何在所有需要使用各种background-colorcolor的组件上设置主题。
  2. changeTheme() 函数的逻辑。它将如何触发所有受影响组件的重新渲染。

谢谢!

【问题讨论】:

    标签: reactjs sass themes


    【解决方案1】:

    最好的方法是使用css variables

    您需要使用 css 变量指定您的主题,并在某些用户操作中在您的网站中添加额外的 css。

    1. 像上面提到的那样创建单个主题

       --color: blue;
       --bg-color: red;
       .theme {
           background-color: var(--bg-color);
           color: (--color);
       }
      
    2. 在您的组件中添加其他样式

      {this.state.useTheme && <style type="text/css">
          :root {
              --color: blue;
              --bg-color: red;
          }   
      </style>}
      
    3. 用户点击时更改标志

      <div onClick={this.setState({useTheme: true})}> Apply theme </div>
      

    或其他变体

    1. 创建额外的theme.css 文件,您可以在其中指定不同的变量

      --bg-color: yellow;
      --color: green;
      
    2. 将它附加到某些用户操作上。代码源来自here

      { var head = document.getElementsByTagName('head')[0]; var link = document.createElement('link'); 链接.id = cssId; link.rel = '样式表'; link.type = '文本/css'; link.href = 'http://your-website.com/path-to-css-file/theme.css'; 链接.媒体 = '全部'; head.appendChild(链接); }}> 改变主题

    这样做可以避免大量代码重复。因为您不需要创建多个主题。您只需要在更改时添加少量的附加 css,因此您可以创建很多主题,甚至让用户自定义它们。

    【讨论】:

    猜你喜欢
    • 2017-09-24
    • 1970-01-01
    • 2021-07-13
    • 2019-12-05
    • 1970-01-01
    • 2015-05-22
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多