【问题标题】:How to use SASS parent selector with sass module in react如何在反应中使用带有 sass 模块的 SASS 父选择器
【发布时间】:2021-02-07 16:16:53
【问题描述】:

考虑以下

styles.module.sass

 .button
     cursor: pointer
     background: transparent
     &.active
       border-left-color: green
       border-left-width: 2px

Button.js

const MyButton = () => {
    return <button className={styles.button}>select this</button>;
};

鉴于这是一个 scss 模块,如何在 className 内附加 .active 类?以下内容不起作用,因为“活动”不在类名重写的上下文中。

const MyButton = () => {
    return <button className={styles.button + "active"}>select this</button>;
};

【问题讨论】:

    标签: javascript reactjs sass react-css-modules


    【解决方案1】:

    只需从类似styles.active 的样式中选择active 类,并在加入时在类之间留一个空格。为此,您可以执行以下任何操作:

    1. 您可以使用更改为className={styles.button + " " + styles.active} 或使用模板字符串:
    const MyButton = () => {
        return <button className={`${styles.button} ${styles.active}`}>select this</button>;
    };
    
    1. 您可以使用classnames
    import classNames from 'classnames'
    const MyButton = () => {
        return <button className={classNames(styles.button styles.active)}>select this</button>;
    };
    
    1. 可以使用patch-styles组件:
    const MyButton = () => {
        return (
            <PatchStyles classNames={styles}>
                <button className="button active">select this</button>
            </PatchStyles>
        );
    };
    

    我个人更喜欢patch-styles 或有时classnames 结合patch-styles。由于patch-styles 为您的代码带来了很大的抽象,因此您无需关心将样式应用于每个地方并在应用活动类时忽略它。它还允许通过更改几行代码来移入或移出 CSS/SCSS 模块。

    关于使用classnames 的好处,请阅读他们的文档。当您的课程取决于某些条件时,这很方便。

    【讨论】:

      【解决方案2】:

      你可以使用合成

      .button
           cursor: pointer
           background: transparent
      
      .activeButton
           composes: button
           border-left-color: green
           border-left-width: 2px
      

      然后在 jsx 中使用.activeButton

      const MyButton = () => {
          return <button className={styles.activeButton}>select this</button>;
      };
      

      【讨论】:

      • 我知道这件事,但这并不能回答问题
      猜你喜欢
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 2013-11-18
      • 2017-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多