如何在我的 React 组件中使用 SCSS 变量

aba*_*edo 14 sass reactjs node-sass

我正在研究一个遵循这种结构的 React 项目

src |
  components |
    Footer |
      index.jsx
      styles.scss
    Header |
      index.jsx
      styles.scss
    scss |
      helpers.scss
      variables.scss
      ...
    main.scss
Run Code Online (Sandbox Code Playgroud)

在我的变量文件中,我使用了css自定义变量,因此,所有这些变量都在那里:root,我可以在我的组件样式中访问它们。

当我想创建深色时,我想使用 SCSS 函数darken,但它不评估它们并抛出一个错误,说这var(--blue)不是有效颜色。

作为解决方案,我决定将所有变量移动到 SCSS 变量中,但是在构建项目时,它会引发另一个错误,指出 a$blue未定义。

我可以使用的唯一解决方案是将变量文件包含在所有样式文件中,但是,我不知道对于我正在使用的结构是否有更好的解决方案。

Nis*_*hah 10

从反应 17

要将您的 scss 变量访问到 react 组件中,您需要执行类似的操作

  1. node-sass作为依赖项或开发依赖项安装
  2. 无需在 webpack 中进行任何配置更改
  3. 作为模块导入 <-- 要点

变量.module.scss

$color: skyblue;
$primaryColor: red;

:export {
    color: $color;
    primary-color: $primaryColor;
}
Run Code Online (Sandbox Code Playgroud)

应用程序.js

import variables from '<YOUR_PATH>/variables.module.scss';

const App = () => {
    console.log(variables);
}
Run Code Online (Sandbox Code Playgroud)


San*_*mar 9

在此处输入图片说明如果你不想使用,styled-component 那么你可以点击这个链接。 https://til.hashrocket.com/posts/sxbrscjuqu-share-scss-variables-with-javascript


mat*_*hew 6

我使用类似的结构来组织 .scss 文件。我喜欢将样式与组件放在同一文件夹中。但是,我将所有 scss 文件导入到我的main.scss文件中。这有助于避免 DOM 中的样式冲突。

主文件

import "./scss/helpers.scss"
import "./variables.scss"
import "./Footer/style.scss"
import "./Header/styles.scss"
Run Code Online (Sandbox Code Playgroud)

确保使用下划线命名文件,以便所有文件在编译时合并。请注意,您不需要在导入中命名下划线。

_helpers.scss
_variable.scss
_style.scss
Run Code Online (Sandbox Code Playgroud)

使用此方法,您只需将样式导入应用程序一次。 index.jsx