CSS Modules - exclude class from being transformed

2019-07-11 05:21发布

问题:

I'm using CSS modules and by far everything was working great.

We started to use external UI library along with our own one, so I'm writing components like this:

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

Assuming that the ExternalUIComponent has its own class that in the final CSS file looks like this external-ui-component, how can I make adjust this component styling from my css file? The below example does not work:

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

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

回答1:

Please do not use inline styles as someone else suggested. Stay away from inline styles as much as you can because they can cause unnecessary re-renders.

You should use global instead.

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

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

Also, I recommend using camel case style names which is the preferred way for css-modules. So your class name would be : .myComponent { ... }

And you can use it in your code as

<div className={ styles.myComponent } >

If you wanted to add more styles , you can use the array.join(' ') syntax.

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

This is cleaner!



回答2:

Did you try inline styles for that component ?

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

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

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