如何在 React 组件中使用 javascript 访问 Sass 变量? [英] How to access Sass variables using javascript inside a react component?

查看:54
本文介绍了如何在 React 组件中使用 javascript 访问 Sass 变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想从 React 组件内的 theme.scss 更改下面显示的 Sass 变量的值.

I just want to change the value of the Sass variables shown below from theme.scss inside a react component.

主题.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])          

推荐答案

您可以使用 CSS 变量 以在以下步骤中实现主题:

You can use CSS variables to achieve themes in below steps:

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

Add a custom data-* attribute in body of index.html file:

<body data-theme="light"> <!-- Let's name it data-theme and start with light -->
  <noscript>You need to enable JavaScript to run this app.</noscript>
  <div id="root"></div>
</body>

并且,为所有(您可以有两个以上的主题)data-* 属性值(即主题)定义您需要的 CSS 变量:

And, define CSS variables, as many as you need, for all (you can have more than two themes) the data-* attribute values i.e. themes:

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
}

而且,这里是一个如何使用这些 CSS 的示例标签(或类)的变量:

And, here is an example how to use these CSS variables for a tag (or class):

body {
  color: var(--color) !important; // Here
  background-color: var(--body-bg) !important; // And, Here
  font-family: 'Segoe UI', 'Roboto'; // Ignore it, just for example
}

// example using in a class
.some-class {
  color: var(--color);
  background-color: var(--body-bg);
}

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

You can now create some utility functions that would switch between the themes:

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

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

您可以在任何组件中导入上述功能以根据需要更改主题.

You can import the above functions in any component to change the theme as you need.

这篇关于如何在 React 组件中使用 javascript 访问 Sass 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆