简体   繁体   English

React CSS 模块中的级联样式

[英]Cascade styles in React CSS module

In my React app I had some messed up combination of inline JS styles and CSS classes.在我的 React 应用程序中,我有一些内联 JS 样式和 CSS 类的混乱组合。 I decided to split up everything into CSS modules that I can use this way:我决定将所有内容拆分为我可以这样使用的 CSS 模块:

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

And use them like JS objects.并像使用 JS 对象一样使用它们。 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.我有类似.selected .option-text东西,即使我确实在外面selected类,因为option-text已更改为唯一名称,它与selected元素内的option-text不匹配。 What is the correct approach to get it matching again, using CSS modules.使用 CSS 模块再次匹配的正确方法是什么。

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='当然,如果子组件特定于父组件并且只使用一次,或者如果父子组合彼此特定,那么也许一种方法是让他们简单地在父级共享 css 导入,然后通过className='将其传递给 child

change the import statement to :将导入语句更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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