反应动态主题

问题描述 投票:1回答:1

我有一个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个回答
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的代码源 <div onClick={() => { var head = document.getElementsByTagName('head')[0]; var link = document.createElement('link'); link.id = cssId; link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'http://your-website.com/path-to-css-file/theme.css'; link.media = 'all'; head.appendChild(link); }}> Change theme </div>

通过这样做,您将避免大量的代码重复。因为您无需创建多个主题。而且你只需要在变化时添加额外的小css,这样你就可以创建很多主题甚至让用户自定义它们。

© www.soinside.com 2019 - 2024. All rights reserved.