Reactjs 如何在react组件中使用javascript访问Sass变量?

Reactjs 如何在react组件中使用javascript访问Sass变量?,reactjs,sass,use-effect,Reactjs,Sass,Use Effect,我只想更改react组件中theme.scss中下面显示的Sass变量的值 theme.scss $backgroundColor: #fff; $secondaryColor: #000; 反应组分 useEffect(() => { // i want to change the Sass variable here inside this hook // so that when the state changes the color changes }, [state])

我只想更改react组件中
theme.scss
中下面显示的Sass变量的值

theme.scss

$backgroundColor: #fff;
$secondaryColor: #000;
反应组分

useEffect(() => {
  // i want to change the Sass variable here inside this hook
  // so that when the state changes the color changes
}, [state])          
您可以使用以下步骤实现主题:

index.html
文件的
body
中添加自定义属性:


您需要启用JavaScript才能运行此应用程序。
并且,根据需要为所有(您可以有两个以上的主题)数据-*属性值定义CSS变量,即主题:

body[data-theme='light'] {
  --body-bg: white;
  --color: black;
}

body[data-theme='dark'] {
  --body-bg: black;
  --color: white;
}

:root {
  --primary-color: green; 
  // you can also set some CSS vars (that are common to all the themes) on :root
}
下面是一个示例,说明如何为标记(或类)创建:

现在,您可以创建一些在主题之间切换的实用程序函数:

export function setLightTheme() {
  document.getElementsByTagName('body')[0].setAttribute('data-theme', 'light')
}

export function setDarkTheme() {
  document.getElementsByTagName('body')[0].setAttribute('data-theme', 'dark')
}

您可以在任何组件中导入上述函数以根据需要更改主题。

您不能动态更改SASS变量,一旦编译了样式,变量就不存在了。您应该改为使用。当我在Sass函数中使用css变量时,会出现错误。。SassError:code>darken($color,$amount)的参数
$color
必须是F:\Projects\REACT Projects\REACT\src\Screens\HomeScreen.scs第39行的颜色,在函数
stdin>>第39行的变暗背景:变暗(var(--原色),3);谢谢你的反馈。当我在Sass函数(比如darken)和自定义函数中使用css变量时,我也会出错。“SassError:argument
$color
of
darken($color,$amount)
必须是F:\Tech Projects\REACT Projects\portfolio\u REACT\src\Screens\HomeScreen.scs第39行的函数
darken
background:darken(var(--原色),3);”这很棘手。试试这个:如果它不起作用,我也可以试试。那个博客建议在Sass中定义一个函数,以及一些额外的变量来应用颜色的亮度,这会使它变得复杂,对我来说也不起作用。我认为在Sass函数中使用CSS变量,比如
darken
,是不可能的(以简单的方式)。因为像
darken
这样的SASS函数被编译并计算成某种颜色值(编译成CSS后没有变量)。你应该考虑其他的主题选项,而不是这个(使用CSS变量)。我试过那个,但从来没有为我工作过。正如你所说,我应该寻找一些其他的主题选项。
export function setLightTheme() {
  document.getElementsByTagName('body')[0].setAttribute('data-theme', 'light')
}

export function setDarkTheme() {
  document.getElementsByTagName('body')[0].setAttribute('data-theme', 'dark')
}