【问题标题】:React CSS module not putting in class names even though they existReact CSS 模块不输入类名,即使它们存在
【发布时间】:2023-01-28 15:54:23
【问题描述】:

我有一个 React 组件,我正在尝试为我的网络应用程序设置按钮样式。我已经用完全相同的方式对其他组件进行了无数次此操作。由于某种原因,呈现的页面中未使用类名。我使用 parceljs 来捆绑我的脚本并检查了浏览器中的源代码,css 类存在。我已经尝试了几个小时来改变周围的事物以使其正常工作但没有运气,所以我正在向社区寻求想法。

按钮.tsx

import * as React from 'react'
import styles from './Button.module.css'
import cx from 'classnames'

type ButtonProps = {
  color?: 'default' | 'primary' | 'alert' | 'success'
  value: string
  onClick?: () => void
}

export const Button: React.FC<ButtonProps> = (props) => {
  const { color = 'default' } = props;
  return (
    <div className={styles.buttonContainer}> {/* part of my testing, tried wrapping everything in a div to see if the style would work */}
      <button className={cx(styles.buttonContainer, styles[color])} onClick={props.onClick}>
        <div className={styles.value}>{props.value}</div>
      </button>
    </div>
  )
}

按钮.module.css

.buttonContainer {
    color: black;
}

.default {
    background: white;
    color: var(--colorBlack100);
}

.primary {
    background: var(--colorBlue80);
    color: white;
}

.alert {
    background: var(--colorAlert);
    color: white;
}

.success {
    background: var(--colorSuccess);
    color: white;
}

.buttonContainer .value {
    color: inherit;
}

index.ts - 用于将所有组件组合在一起

...
export { Checkbox } from './Checkbox/Checkbox'
...

Index.tsx - 显示它的页面

import * as React from 'react'
import { Button } from '../Components'

const Index: React.FC = () => {
  return (
    <div>
      <Button value="Default" onClick={() => console.log("test")} color="primary" />
    </div>
  )
}

export default Index

这是呈现的 Button div

<div><button class=""><div>Default</div></button></div>

这是我使用 Chrome 开发工具从源代码中提取的来自 parcel 的 css,这些类存在所以我知道 parcel 正在拾取它

._9p9acG_buttonContainer {
  color: #000;
}

._9p9acG_default {
  color: var(--colorBlack100);
  background: #fff;
}

._9p9acG_primary {
  background: var(--colorBlue80);
  color: #fff;
}

._9p9acG_alert {
  background: var(--colorAlert);
  color: #fff;
}

._9p9acG_success {
  background: var(--colorSuccess);
  color: #fff;
}

._9p9acG_buttonContainer ._9p9acG_value {
  color: inherit;
}

如前所述,我已经用许多其他组件成功地做到了这一点,这是唯一一个表现得很有趣的组件,我不知所措。

预先感谢您的帮助。

【问题讨论】:

    标签: reactjs parceljs react-css-modules


    【解决方案1】:

    我不知道为什么,但是在删除文件并一次添加每行 1 并测试直到它不再起作用之后,我发现它是 CSS 类名 .default 导致它不起作用。这是某种保留字吗?我唯一的其他猜测是它是 parceljs 或 react-css-modules 中的错误。

    【讨论】:

      猜你喜欢
      • 2020-11-29
      • 2019-07-26
      • 2022-07-20
      • 1970-01-01
      • 2021-03-16
      • 2011-11-14
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多