最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - CSS Modules: Why Are External Styles Not Overriding Base Styles? - Stack Overflow

programmeradmin7浏览0评论

I'm having trouble with CSS Modules in React when trying to override base styles with external ones. The styles passed via className don't seem to take precedence as expected.

Problem Description

  1. I have a button with base styles (styles.mainButton).
  2. I want to override/add styles from an external source (styles.propButtonStyle).
  3. When combining them with clsx, the first case works, but the other two don't.How many are used in one file

Why do external styles (styles.propButtonStyle) not override base styles in cases 2?

import styles from "./page.module.css";
import stylesOtherFile from "./test.module.scss";

// 1. ✅ Works (styles.propButtonStyle overrides correctly)
<button className={clsx(styles.mainButton, styles.propButtonStyle)} />

// 2. ❌ Doesn't work (styles.propButtonStyle is ignored)
<button className={clsx(stylesOtherFile.mainButton, styles.propButtonStyle)} />

./page.module.css has styles

.mainButton {
  width: fit-content;
}

.propButtonStyle {
  width: 100%;
}

./test.module.scss has styles

.mainButton {
  width: fit-content;
}

And if we create a component ButtonTest

// 1. ✅ Works (styles.propButtonStyle overrides correctly)
<button className={clsx(styles.mainButton, styles.propButtonStyle)} />

// 2. ❌ Doesn't work (styles.propButtonStyle is ignored)
<button className={clsx(stylesOtherFile.mainButton, styles.propButtonStyle)} />

// 3. ❌ Doesn't work (inside a custom component)
<ButtonTest className={styles.propButtonStyle} />

ButtonTest.tsx

import clsx from 'clsx';
import styles from './button.module.css';

export const ButtonTest = ({ children, className }) => {
  return <button className={clsx(styles.button, className)}>{children}</button>;
};

.button {
  width: fit-content;
}

发布评论

评论列表(0)

  1. 暂无评论