简体   繁体   English

根据 SCSS 中的变量更改调色板

[英]Change color palette depending on variable in SCSS

I have multiple components in my react app using a top navbar, sidebar, cards, etc. All share the same color palette (assets/css/variables.scss):我的 React 应用程序中有多个组件使用顶部导航栏、侧边栏、卡片等。所有组件都共享相同的调色板 (assets/css/variables.scss):

$nav-color: #009788;
$side-color: #9be7db;
$side-color-selected: #84ebdb;

What I want to do is to change these three colors depending on a variable, for example, a boolean returned by the login.我想做的是根据一个变量改变这三个colors,比如登录返回的一个boolean。 Is this posible to achieve in the variable.scss file?这可能在 variable.scss 文件中实现吗?

Obviously, I want to keep the variables names cause all the components use these variables.显然,我想保留变量名称,因为所有组件都使用这些变量。 I only want to change the variables values.我只想更改变量值。

You cannot do it purely with Sass, because sass is pre-rendered to CSS, so any variables are resolved to a value by the time they are delivered to the browser.你不能纯粹用 Sass 来做,因为 sass 被预渲染为 CSS,所以任何变量在传递给浏览器时都会被解析为一个值。 However , you can point the Sass variables to CSS Custom Properties (Variables) and then update the value of the CSS variables with JS at your whim.但是,您可以将Sass变量指向CSS自定义属性(变量) ,然后随心所欲地用JS更新CSS变量的值。 Below is an example with CSS only-- but you can point Sass vars at CSS vars .下面是一个仅包含 CSS 的示例——但您可以将 Sass 变量指向 CSS 变量

 document.querySelector('#toggleTheme').addEventListener('click', () => { const themeVar = '--theme-color'; const themeColor = document.body.style.getPropertyValue(themeVar); const newThemeColor = themeColor === 'red'? 'blue': 'red'; document.body.style.setProperty(themeVar, newThemeColor); });
 :root { --theme-color: red; } h1 { color: var(--theme-color); }
 <h1>Hello World</h1> <button id="toggleTheme">Toggle Theme Color</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM