我有一个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() }
可以这样做吗?具体来说,我想弄清楚这两部分:
background-color
和color
的所有组件上设置主题。changeTheme()
函数的逻辑。如何在所有受影响的组件上触发重新渲染。谢谢!
最好的方法是使用css variables。
您需要使用css变量指定主题,并在某些用户操作中在您的站点中添加其他css。
--color: blue;
--bg-color: red;
.theme {
background-color: var(--bg-color);
color: (--color);
}
{this.state.useTheme && <style type="text/css">
:root {
--color: blue;
--bg-color: red;
}
</style>}
<div onClick={this.setState({useTheme: true})}> Apply theme </div>
或另一种变体
theme.css
文件,您可以在其中指定不同的变量
--bg-color: yellow;
--color: green;
<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,这样你就可以创建很多主题甚至让用户自定义它们。