Sass ID选择器在React和create-react-library中不起作用

I have a library I'm making with a Header component and a Button component. I gave them ID's to identify them in my SASS file, this is my current situation:

index.js:

import React from 'react'
import './styles.module.scss'

export const Button = ({text, bgColor, textColor, fontFamily}) => {

  return <button id="button" style={
    {backgroundColor: [bgColor],
    color: [textColor],
    fontFamily: [fontFamily]}
  }>{text}</button>
}

export const Header = ({text, size, fontFamily, textColor}) => {
  return <h1 style={{
    fontSize: [size],
    fontFamily: [fontFamily],
    color: [textColor]
  }} id="header">{text}</h1>
}

export const subHeader = () => {
  return null
}

styles.module.scss:

@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;700&display=swap');
$font: 'Montserrat',
sans-serif;
$blue: #1778f2;
#button {
    background: $blue;
    border: none;
    color: white;
    padding: 1em 2em;
    border-radius: 10px;
    font-family: $font;
    font-weight: 500;
    font-size: 1.2em;
    line-height: .8em;
    cursor: pointer;
    &:focus {
        outline: none;
    }
}

#header {
    font-family: $font;
    margin: 0;
    font-size: 3em;
}

那是行不通的。但是,当我将scss文件中的ID选择器替换为HTML(按钮,h1)中的元素名称时,它可以工作:

button {
    background: $blue;
    border: none;
    color: white;
    padding: 1em 2em;
    border-radius: 10px;
    font-family: $font;
    font-weight: 500;
    font-size: 1.2em;
    line-height: .8em;
    cursor: pointer;
    &:focus {
        outline: none;
    }
}

h1 {
    font-family: $font;
    margin: 0;
    font-size: 3em;
}

这是什么问题它是sass(我是新手,顺便说一句,我安装了node sass,所以它应该可以工作)还是其他?提前致谢。

评论
伊筱沫
伊筱沫

You can either rename your scss file to remove the module from file name:

import './styles.scss'

or if you want to use module pattern in your file name, do this:

import styles form './styles.module.scss'

并以这种方式提供ID /类:

export const Button = ({text, bgColor, textColor, fontFamily}) => {

  return <button id={styles.button} style={ // or className={styles.myClass1}
    {backgroundColor: [bgColor],
    color: [textColor],
    fontFamily: [fontFamily]}
  }>{text}</button>
}

export const Header = ({text, size, fontFamily, textColor}) => {
  return <h1 style={{
    fontSize: [size],
    fontFamily: [fontFamily],
    color: [textColor]
  }} id={styles.header}>{text} // or className={styles.myClass2}
  </h1>
}

此行为通常由诸如webpack,browserify等捆绑程序实现。这不是sass的固有功能。

当您将此模块模式用于Sass时,生成的样式表看起来像这样:

.moduleName_className__someUniqueId { // for classes
  color: red; 
}

#.moduleName_myId__someUniqueId { // for IDs
  color: blue; 
}

它解决什么问题?

It provides you unique selectors (IDs and classnames) by adding moduleName and a unique identifier with them. Which helps you keep your styles organized and separated.

点赞
评论