我有一个 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;
将其附加到某些用户操作上。代码来源来自 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'; link.media = '全部'; head.appendChild(链接); }}> 改变主题
通过这样做,您将避免大量代码重复。因为您不需要创建多个主题。您只需要在更改时添加少量额外的 css,这样您就可以创建很多主题,甚至让用户自定义它们。
关于reactjs - react 动态主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52261260/