【问题标题】:Is there a way to dynamically update scss variables using JS in react?有没有办法在反应中使用 JS 动态更新 scss 变量?
【发布时间】:2021-02-20 02:13:29
【问题描述】:

问题

我在colors.scss 文件中有两个 scss 变量 位置,我想根据逻辑从 javascript 仅更新变量颜色 ,

if(day){
  // update $backgroundColor to white
}else{
  // update $backgroundColor to black
}

更多信息:

我尝试过 :export{} 不起作用,也尝试过 document.documentElement.style.setProperty 使用全局 css 变量。我正在使用 reactjs 进行前端开发。

【问题讨论】:

  • 您可以使用 classnames 包来帮助您管理 javascript 中的 scss 类。

标签: javascript css reactjs sass scss-mixins


【解决方案1】:

您可以将 css 变量分配给$backgroundColor as

:root {
  --background-color: white;
}
$backgroundColor: var(--background-color);

并将js中的变量更新为

 const day = true;
 const root = document.documentElement;
 root.style.setProperty('--background-color', day ? 'white' : 'black');

【讨论】:

    【解决方案2】:

    您无法更新 scss 变量,因为它们在运行时(运行 JS 时)不存在。

    您可以创建 2 个类,每种样式一个,并在运行时应用其中一个类。

    【讨论】:

    • 在某种程度上你是对的,我们不能直接更新 scss 变量,因此有一个 css 变量占位符有助于动态更新。
    猜你喜欢
    • 2020-06-04
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 2016-05-31
    • 2020-04-27
    • 2016-05-23
    • 1970-01-01
    • 2021-10-22
    相关资源
    最近更新 更多