React
React 中引入 CSS 的方式
React 本身不限制样式方案,常见方式有四种。
一、外部样式表
直接 import CSS 文件,样式全局生效:
import './styles.css'简单直接,但类名是全局的,存在命名冲突风险。
二、内联样式
通过 style 属性传入对象,属性名用驼峰命名:
<div style={{ backgroundColor: 'red', fontSize: '14px' }} />适合动态样式,但不支持伪类(:hover)和媒体查询。
三、CSS Modules
文件名加 .module.css,类名自动局部化,不会污染全局:
.button {
color: white;
background: blue;
}import styles from './Button.module.css'
function Button() {
return <button className={styles.button}>Click me</button>
}类名在编译时被转换为唯一哈希,天然避免冲突。
四、CSS-in-JS
用 JS 写样式,代表库是 styled-components 和 emotion:
| 方式 | 原理 | 代表库 |
|---|---|---|
| 运行时注入 | 使用 useInsertionEffect 注入 <style> | styled-components、emotion |
| 零运行时 | 构建时提取为静态 CSS 文件 | vanilla-extract、Linaria |
运行时方案灵活但有性能开销(触发浏览器重新计算样式);零运行时无运行时开销,适合对性能敏感的场景。
五、条件样式
动态拼接类名有两种常用写法:
// 模板字符串
function Demo1(params: type) {
return <div className={`base ${isActive ? 'active' : ''}`} />
}
// classnames 库(推荐,更清晰)
import classNames from 'classnames'
function Demo2(params: type) {
return (
<div
className={classNames('base', { active: isActive, disabled: isDisabled })}
/>
)
}六、方案对比
| 方式 | 作用域 | 动态样式 | 构建依赖 |
|---|---|---|---|
| 外部样式表 | 全局 | 弱 | 无 |
| 内联样式 | 组件 | 强 | 无 |
| CSS Modules | 组件 | 弱 | 需要 |
| CSS-in-JS | 组件 | 强 | 需要 |
七、一句话记忆
小项目用 CSS Modules 够用;需要动态主题或设计系统选 CSS-in-JS;性能敏感场景优先零运行时方案。