Emotion简介 #
什么是Emotion? #
Emotion 是一个专为 JavaScript 应用设计的 CSS-in-JS 库,它允许你在 JavaScript 中编写 CSS 样式。Emotion 结合了传统 CSS 的表达力和 JavaScript 的动态能力,提供了一种优雅的方式来管理 React 应用的样式。
为什么选择Emotion? #
1. 两种使用方式 #
Emotion 提供了两种灵活的使用方式:
css prop 方式:
jsx
import { css } from '@emotion/react'
function App() {
return (
<div
css={css`
padding: 32px;
background-color: hotpink;
font-size: 24px;
border-radius: 4px;
&:hover {
color: white;
}
`}
>
Hover to change color.
</div>
)
}
styled 方式:
jsx
import styled from '@emotion/styled'
const Button = styled.button`
padding: 32px;
background-color: hotpink;
font-size: 24px;
border-radius: 4px;
color: black;
font-weight: bold;
&:hover {
color: white;
}
`
function App() {
return <Button>Click me</Button>
}
2. 核心优势 #
- 零配置:开箱即用,无需复杂配置
- 高性能:优化的运行时,极快的样式注入
- 类型安全:完整的 TypeScript 支持
- 服务端渲染:简单的 SSR 配置
- 样式隔离:自动生成唯一类名,避免样式冲突
- 动态样式:基于 props 轻松创建动态样式
- 主题支持:内置主题系统
3. 与传统CSS对比 #
| 特性 | 传统CSS | Emotion |
|---|---|---|
| 样式隔离 | 需要手动管理 | 自动隔离 |
| 动态样式 | 需要JS操作 | 直接使用props |
| 主题切换 | CSS变量 | ThemeProvider |
| 代码组织 | 分离文件 | 组件内聚 |
| 死代码消除 | 困难 | 自动处理 |
应用场景 #
1. React组件库开发 #
Emotion 非常适合开发可复用的组件库:
jsx
import styled from '@emotion/styled'
export const Card = styled.div`
background: white;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
padding: ${props => props.padding || '16px'};
`
export const Button = styled.button`
background: ${props => props.primary ? '#007bff' : '#6c757d'};
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
cursor: pointer;
&:hover {
opacity: 0.9;
}
`
2. 主题化应用 #
轻松实现深色/浅色主题切换:
jsx
import { ThemeProvider } from '@emotion/react'
const lightTheme = {
colors: {
primary: '#007bff',
background: '#ffffff',
text: '#333333'
}
}
const darkTheme = {
colors: {
primary: '#4da3ff',
background: '#1a1a1a',
text: '#ffffff'
}
}
function App() {
return (
<ThemeProvider theme={lightTheme}>
<Application />
</ThemeProvider>
)
}
3. 动态样式 #
根据组件状态动态调整样式:
jsx
import styled from '@emotion/styled'
const Input = styled.input`
padding: 12px;
border: 2px solid ${props => props.error ? '#dc3545' : '#ced4da'};
border-radius: 4px;
&:focus {
border-color: ${props => props.error ? '#dc3545' : '#007bff'};
outline: none;
}
`
Emotion的工作原理 #
1. 样式注入 #
Emotion 在运行时将 CSS 样式注入到页面的 <style> 标签中:
text
组件渲染 → 解析样式 → 生成类名 → 注入<style> → 应用到元素
2. 类名生成 #
Emotion 会为每个唯一的样式组合生成一个唯一的类名:
jsx
// 相同样式 → 相同类名
<div css={{ color: 'red' }} /> // → css-1xyz
<div css={{ color: 'red' }} /> // → css-1xyz
// 不同样式 → 不同类名
<div css={{ color: 'red' }} /> // → css-1xyz
<div css={{ color: 'blue' }} /> // → css-2abc
3. 样式缓存 #
Emotion 会缓存已生成的样式,避免重复计算,提高性能。
Emotion生态系统 #
| 包名 | 用途 |
|---|---|
| @emotion/react | React 集成核心 |
| @emotion/styled | styled-components 风格 API |
| @emotion/cache | 样式缓存管理 |
| @emotion/server | SSR 服务端支持 |
| @emotion/native | React Native 支持 |
| @emotion/primitives | React Primitives 支持 |
总结 #
Emotion 是一个功能强大、性能优异的 CSS-in-JS 解决方案。它提供了灵活的使用方式、完整的类型支持和优秀的开发体验,是现代 React 应用样式管理的理想选择。
继续学习 Emotion安装,开始搭建你的开发环境。
最后更新:2026-03-28