CSS 模块 - 从转换中排除 class

CSS Modules - exclude class from being transformed

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

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

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

假设 ExternalUIComponent 有自己的 class,在最终的 CSS 文件中看起来像这样 external-ui-component,我如何从我的css 文件?以下示例不起作用:

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

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

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

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

const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')',
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!</div>;
}

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

您应该改用 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 模块的首选方式。 所以您的 class 名称将是:.myComponent { ... }

您可以在代码中将其用作

<div className={ styles.myComponent } >

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

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

这个更干净!

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

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