简体   繁体   中英

Cascade styles in React CSS module

In my React app I had some messed up combination of inline JS styles and CSS classes. I decided to split up everything into CSS modules that I can use this way:

import styles from './ImageTextOption.module.css'

And use them like JS objects. However, now styles don't cascade from parent elements (that aren't defined in the same module). I had something like .selected .option-text , and even though I do have selected class outside, because option-text has changed into a unique name it doesn't match the option-text inside selected element. What is the correct approach to get it matching again, using CSS modules.

I've run into the same challenge and have found it easier at times to pass styles as props to your child components. This is a good pattern if you are reusing the child component in different places.

Here is an example that accomplishes the very same.

Of course if the child component is specific to the parent component and is only used once, or if the parent-child combination is specific to each other, then maybe an approach would be for them to simply share the the css import at the parent level, then pass it down to child via className='

change the import statement to :

import './<<"PathToCss">>'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM