【问题标题】:CSS Modules - exclude class from being transformedCSS 模块 - 排除类被转换
【发布时间】:2019-03-06 17:02:02
【问题描述】:

我正在使用 CSS 模块,到目前为止一切都很好。

我们开始使用外部 UI 库和我们自己的 UI 库,所以我正在编写这样的组件:

<div className={styles['my-component']}>
   <ExternalUIComponent />
</div>

假设ExternalUIComponent 有自己的类,在最终的CSS 文件中看起来像这样external-ui-component,我怎样才能从我的css 文件中调整这个组件样式?下面的例子不起作用:

.my-component {
   font-size: 1em;
}

.my-component .external-ui-component {
   padding: 16px;
   // Some other styling adjustments here
}

【问题讨论】:

    标签: css reactjs css-modules


    【解决方案1】:

    请不要像其他人建议的那样使用内联样式。尽可能远离内联样式,因为它们会导致不必要的重新渲染。

    您应该改用global

    .my-component {
        :global {
            .external-ui-component {
               padding: 16px;
               // Some other styling adjustments here
            }
        }
    }
    

    https://github.com/css-modules/css-modules#usage-with-preprocessors

    另外,我建议使用驼峰式样式名称,这是 css 模块的首选方式。 所以你的班级名称是:.myComponent { ... }

    你可以在你的代码中使用它

    <div className={ styles.myComponent } >
    

    如果您想添加更多样式,可以使用array.join(' ') 语法。

    <div className={ [ styles.myComponent, styles.anotherStyle ].join(' ') } >
    

    这样更干净!

    【讨论】:

    • 谢谢,:global 是我正在寻找的东西,但文档对我来说并不清楚!当涉及到多个类时 - 我更喜欢 classnames 包 :)
    • 我更喜欢使用尽可能少的 3rd 方库。因为更多的库会增加捆绑文件的大小,并增加项目的依赖性,这意味着额外的潜在错误!但是做任何你喜欢做的事情:)
    • 使用子类时不适合我
    【解决方案2】:

    这是纯 CSS 中的一种较短形式(即不需要预处理器):

    .my-component :global .external-ui-component {
       // ...
    }
    

    【讨论】:

    • 这确实好多了,谢谢
    【解决方案3】:

    您是否尝试过该组件的内联样式?

    https://reactjs.org/docs/dom-elements.html#style

    const divStyle = {
      color: 'blue',
      backgroundImage: 'url(' + imgUrl + ')',
    };
    
    function HelloWorldComponent() {
      return <div style={divStyle}>Hello World!</div>;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-25
      • 2022-01-22
      • 2020-04-27
      • 2021-07-21
      • 2015-10-03
      • 2011-04-20
      • 1970-01-01
      • 2016-01-09
      • 2011-06-20
      相关资源
      最近更新 更多