Skip to content
鼓励作者:欢迎打赏犒劳

react的样式

在 React 中,不推荐大量使用内联样式style 属性),因为它有诸多限制:

  • 不支持伪类(:hover:focus 等)、媒体查询、动画(@keyframes)。
  • 无法复用样式,每个元素都要重复写对象。
  • 性能略差(每次渲染都会创建新对象,尽管影响很小)。
  • 调试不便(生成的是动态属性名)。

少量动态、计算出的样式(如根据状态改变 widthtransform)用内联可以接受,但作为主要样式方案会很麻烦。


方案一:新建单独的 CSS 文件(最传统、简单)

  • 新建 ComponentName.css(或 .scss.module.css 等)。
  • 在组件文件中导入:import './ComponentName.css'
  • 使用 className="..." 而不是 class
jsx
// Button.jsx
import './Button.css';

function Button() {
  return <button className="btn-primary">Click</button>;
}
css
/* Button.css */
.btn-primary {
  background: blue;
  color: white;
}

方案二:CSS Modules(推荐,避免全局污染)

  • 文件名必须为 *.module.css(如 Button.module.css)。
  • 导入为一个对象:import styles from './Button.module.css'
  • 使用 className={styles.btnPrimary}(会自动生成唯一类名)。
jsx
import styles from './Button.module.css';

function Button() {
  return <button className={styles.btnPrimary}>Click</button>;
}

方案三:行内样式

jsx
<h1  style={{ textAlign: 'center', color: '#333' }}>
    🛍️ 产品展示中心
</h1>

如有转载或 CV 的请标注本站原文地址