CSS Modules - referencing classes from other modules

假装没事ソ 提交于 2019-12-05 17:48:47

This is a common issue when migrating to CSS Modules. In short, a css module cannot override a style from another css module, and this is by design. Styles are supposed to live with the components that render them, and nowhere else.

What you can do to refactor this is to create a component style variant and explicitly set the variant through a prop when rendered within your wrapper.

For example, suppose your headline component currently looks something like this:

CSS

.headline {
  color: green;
}

JSX

import styles from "Headline.css";
const Headline = () => {
  return (
    <div className={styles.headline} />
  );
}

Rather than trying to override the .headline class name from somewhere else, you can create a variant class name that you toggle through a prop:

CSS

.headline-green {
  color: green;
}

.headline-orange {
  color: orange;
}

JSX

import styles from "Headline.css";
const Headline = ({orange}) => {
  return (
    <div className={orange ? styles.headlineOrange : styles.headlineGreen} />
  );
}

And when you render it from your wrapper, set it to the orange variant:

<Headline orange />

Tip: you can use composes to eliminate duplicate common styles between your variants.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!