跳转到内容
主菜单
主菜单
移至侧栏
隐藏
导航
首页
最近更改
随机页面
MediaWiki帮助
代码酷
搜索
搜索
中文(中国大陆)
外观
创建账号
登录
个人工具
创建账号
登录
未登录编辑者的页面
了解详情
贡献
讨论
编辑“︁
Next.js Emotion
”︁
页面
讨论
大陆简体
阅读
编辑
编辑源代码
查看历史
工具
工具
移至侧栏
隐藏
操作
阅读
编辑
编辑源代码
查看历史
常规
链入页面
相关更改
特殊页面
页面信息
外观
移至侧栏
隐藏
您的更改会在有权核准的用户核准后向读者展示。
警告:
您没有登录。如果您进行任何编辑,您的IP地址会公开展示。如果您
登录
或
创建账号
,您的编辑会以您的用户名署名,此外还有其他益处。
反垃圾检查。
不要
加入这个!
= Next.js Emotion = '''Next.js Emotion''' 是一种在 Next.js 框架中使用的 CSS-in-JS 样式解决方案,它结合了 Emotion 库的强大功能和 Next.js 的服务端渲染(SSR)及静态生成(SSG)能力。Emotion 提供了高性能的样式编写方式,支持动态样式、主题切换和组件化 CSS,同时保持优秀的开发体验。 == 介绍 == Emotion 是一个流行的 CSS-in-JS 库,允许开发者直接在 JavaScript 或 TypeScript 中编写样式。在 Next.js 中集成 Emotion,可以充分利用其 SSR 和 SSG 优化能力,同时享受 Emotion 的灵活性和性能优势。 Emotion 的主要特点包括: * 支持静态提取 CSS,减少运行时开销 * 提供 `css` prop 和 `styled` API 两种主要使用方式 * 支持嵌套选择器、伪类和媒体查询 * 内置自动厂商前缀和源映射支持 * 与 React 组件深度集成 == 安装与配置 == 要在 Next.js 项目中使用 Emotion,首先需要安装必要的依赖: <syntaxhighlight lang="bash"> npm install @emotion/react @emotion/styled # 或 yarn add @emotion/react @emotion/styled </syntaxhighlight> 对于 TypeScript 用户,还需要安装类型定义: <syntaxhighlight lang="bash"> npm install --save-dev @types/emotion__react @types/emotion__styled </syntaxhighlight> == 基本用法 == Emotion 在 Next.js 中有两种主要使用方式:通过 `css` prop 和 `styled` API。 === 使用 css prop === <syntaxhighlight lang="javascript"> /** @jsxImportSource @emotion/react */ import { css } from '@emotion/react' function MyComponent() { return ( <div css={css` background-color: hotpink; &:hover { color: white; } `} > This has a hotpink background. </div> ) } </syntaxhighlight> === 使用 styled API === <syntaxhighlight lang="javascript"> import styled from '@emotion/styled' const Button = styled.button` background: transparent; border-radius: 3px; border: 2px solid palevioletred; color: palevioletred; margin: 0.5em 1em; padding: 0.25em 1em; &:hover { background-color: palevioletred; color: white; } ` function MyComponent() { return <Button>Styled Button</Button> } </syntaxhighlight> == 高级特性 == === 主题支持 === Emotion 提供了完整的主题支持,可以通过 `ThemeProvider` 在整个应用中共享主题变量: <syntaxhighlight lang="javascript"> import { ThemeProvider } from '@emotion/react' const theme = { colors: { primary: 'hotpink', secondary: 'blue' } } function App() { return ( <ThemeProvider theme={theme}> <MyComponent /> </ThemeProvider> ) } </syntaxhighlight> 在组件中使用主题: <syntaxhighlight lang="javascript"> import { useTheme } from '@emotion/react' function ThemedComponent() { const theme = useTheme() return ( <div css={{ color: theme.colors.primary }}> This text uses the primary color from theme </div> ) } </syntaxhighlight> === 服务端渲染 === Next.js 与 Emotion 的 SSR 集成需要额外配置。在 `_document.js` 中添加: <syntaxhighlight lang="javascript"> import Document, { Head, Html, Main, NextScript } from 'next/document' import { extractCritical } from '@emotion/server' export default class MyDocument extends Document { static async getInitialProps(ctx) { const initialProps = await Document.getInitialProps(ctx) const styles = extractCritical(initialProps.html) return { ...initialProps, styles: ( <> {initialProps.styles} <style data-emotion-css={styles.ids.join(' ')} dangerouslySetInnerHTML={{ __html: styles.css }} /> </> ) } } render() { return ( <Html lang="en"> <Head /> <body> <Main /> <NextScript /> </body> </Html> ) } } </syntaxhighlight> == 性能优化 == Emotion 在 Next.js 中提供了多种性能优化选项: 1. '''静态提取''':通过 Babel 插件提取静态 CSS 2. '''缓存''':利用 Emotion 的缓存机制减少重复样式计算 3. '''关键 CSS''':使用 `extractCritical` 只发送渲染首屏所需样式 == 实际应用案例 == 以下是一个完整的 Next.js 页面组件示例,展示了 Emotion 的实际应用: <syntaxhighlight lang="javascript"> /** @jsxImportSource @emotion/react */ import { css } from '@emotion/react' import styled from '@emotion/styled' const Container = styled.div` max-width: 1200px; margin: 0 auto; padding: 20px; ` const Title = styled.h1` color: ${props => props.theme.colors.primary}; text-align: center; ` function HomePage() { return ( <Container> <Title>Welcome to Next.js with Emotion</Title> <div css={css` display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; `}> {[1, 2, 3].map(item => ( <div key={item} css={{ padding: '20px', border: '1px solid #ddd', borderRadius: '4px' }}> Card {item} </div> ))} </div> </Container> ) } export default HomePage </syntaxhighlight> == 与其他样式方案比较 == {| class="wikitable" |- ! 特性 !! Emotion !! CSS Modules !! Styled JSX !! Tailwind CSS |- | SSR 支持 || ✔️ || ✔️ || ✔️ || ✔️ |- | 动态样式 || ✔️ || ❌ || 部分 || 部分 |- | 主题支持 || ✔️ || ❌ || ❌ || 通过配置 |- | 学习曲线 || 中等 || 低 || 低 || 中等 |- | 运行时大小 || 中等 || 无 || 小 || 大 |} == 最佳实践 == 1. 对于可重用组件,优先使用 `styled` API 2. 对于一次性样式,使用 `css` prop 3. 合理组织主题变量,避免硬编码颜色和尺寸 4. 利用 Emotion 的 `@emotion/babel-plugin` 进行编译时优化 5. 在大型项目中,考虑将样式与组件分离到单独文件中 == 常见问题 == === 为什么需要 @jsxImportSource 注释? === 这是为了告诉 Babel 使用 Emotion 的 JSX 转换而不是 React 的默认转换。在 Next.js 中,也可以通过修改 Babel 配置来全局设置。 === 如何禁用 Emotion 的开发样式标签? === 在生产环境中,Emotion 会自动使用更高效的样式标签。如果需要手动控制,可以设置: <syntaxhighlight lang="javascript"> import { CacheProvider } from '@emotion/react' import createCache from '@emotion/cache' const cache = createCache({ key: 'my-prefix', speedy: process.env.NODE_ENV === 'production' }) function App() { return ( <CacheProvider value={cache}> {/* 你的应用 */} </CacheProvider> ) } </syntaxhighlight> == 总结 == Next.js Emotion 提供了强大而灵活的样式解决方案,特别适合需要动态样式、主题支持和 SSR 优化的项目。通过合理使用 Emotion 的各种特性,开发者可以创建高性能、可维护的样式系统,同时享受优秀的开发体验。 [[Category:后端框架]] [[Category:Next.js]] [[Category:Next.js样式解决方案]]
摘要:
请注意,所有对代码酷的贡献均被视为依照知识共享署名-非商业性使用-相同方式共享发表(详情请见
代码酷:著作权
)。如果您不希望您的文字作品被随意编辑和分发传播,请不要在此提交。
您同时也向我们承诺,您提交的内容为您自己所创作,或是复制自公共领域或类似自由来源。
未经许可,请勿提交受著作权保护的作品!
取消
编辑帮助
(在新窗口中打开)