N Next.js 中文
原文 ↗

如何使用 CSS-in-JS 库

在 Next.js 中使用 CSS-in-JS 库

更新于 2026-11-06Next.js 16.4.6

警告:

将 CSS-in-JS 与服务器组件和流式渲染等较新的 React 特性一起使用,需要库作者支持最新版本的 React,包括并发渲染。

以下库在 app 目录中的客户端组件里受支持(按字母顺序):

以下库目前正在开发相关支持:

须知:

我们正在测试不同的 CSS-in-JS 库,并将为支持 React 18 特性和/或 app 目录的库添加更多示例。

在 app 中配置 CSS-in-JS

配置 CSS-in-JS 是一个三步式的选择启用过程,包括:

  1. 一个样式注册表,用于在一次渲染中收集所有 CSS 规则。
  2. 使用 useServerInsertedHTML hook 在可能用到这些规则的任何内容之前注入规则。
  3. 一个客户端组件,在初始服务器端渲染期间用样式注册表包裹你的应用。

styled-jsx

在客户端组件中使用 styled-jsx 需要使用 v5.1.0。首先,创建一个新的注册表:

TypeScript

app/registry.tsxtsx
'use client'

import React, { useState } from 'react'
import { useServerInsertedHTML } from 'next/navigation'
import { StyleRegistry, createStyleRegistry } from 'styled-jsx'

export default function StyledJsxRegistry({
  children,
}: {
  children: React.ReactNode
}) {
  // Only create stylesheet once with lazy initial state
  // x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
  const [jsxStyleRegistry] = useState(() => createStyleRegistry())

  useServerInsertedHTML(() => {
    const styles = jsxStyleRegistry.styles()
    jsxStyleRegistry.flush()
    return <>{styles}</>
  })

  return <StyleRegistry registry={jsxStyleRegistry}>{children}</StyleRegistry>
}

JavaScript

app/registry.jsjsx
'use client'

import React, { useState } from 'react'
import { useServerInsertedHTML } from 'next/navigation'
import { StyleRegistry, createStyleRegistry } from 'styled-jsx'

export default function StyledJsxRegistry({ children }) {
  // Only create stylesheet once with lazy initial state
  // x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
  const [jsxStyleRegistry] = useState(() => createStyleRegistry())

  useServerInsertedHTML(() => {
    const styles = jsxStyleRegistry.styles()
    jsxStyleRegistry.flush()
    return <>{styles}</>
  })

  return <StyleRegistry registry={jsxStyleRegistry}>{children}</StyleRegistry>
}

然后,用该注册表包裹你的根布局:

TypeScript

app/layout.tsxtsx
import StyledJsxRegistry from './registry'

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html>
      <body>
        <StyledJsxRegistry>{children}</StyledJsxRegistry>
      </body>
    </html>
  )
}

JavaScript

app/layout.jsjsx
import StyledJsxRegistry from './registry'

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <StyledJsxRegistry>{children}</StyledJsxRegistry>
      </body>
    </html>
  )
}

在此查看示例。

Styled Components

以下是配置 styled-components@6 或更新版本的示例:

首先,在 next.config.js 中启用 styled-components。

next.config.jsjs
module.exports = {
  compiler: {
    styledComponents: true,
  },
}

然后,使用 styled-components API 创建一个全局注册表组件,用于收集一次渲染期间生成的所有 CSS 样式规则,并创建一个返回这些规则的函数。接着使用 useServerInsertedHTML hook 将注册表中收集的样式注入到根布局中的 <head> HTML 标签中。

TypeScript

lib/registry.tsxtsx
'use client'

import React, { useState } from 'react'
import { useServerInsertedHTML } from 'next/navigation'
import { ServerStyleSheet, StyleSheetManager } from 'styled-components'

export default function StyledComponentsRegistry({
  children,
}: {
  children: React.ReactNode
}) {
  // Only create stylesheet once with lazy initial state
  // x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
  const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet())

  useServerInsertedHTML(() => {
    const styles = styledComponentsStyleSheet.getStyleElement()
    styledComponentsStyleSheet.instance.clearTag()
    return <>{styles}</>
  })

  if (typeof window !== 'undefined') return <>{children}</>

  return (
    <StyleSheetManager sheet={styledComponentsStyleSheet.instance}>
      {children}
    </StyleSheetManager>
  )
}

JavaScript

lib/registry.jsjsx
'use client'

import React, { useState } from 'react'
import { useServerInsertedHTML } from 'next/navigation'
import { ServerStyleSheet, StyleSheetManager } from 'styled-components'

export default function StyledComponentsRegistry({ children }) {
  // Only create stylesheet once with lazy initial state
  // x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
  const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet())

  useServerInsertedHTML(() => {
    const styles = styledComponentsStyleSheet.getStyleElement()
    styledComponentsStyleSheet.instance.clearTag()
    return <>{styles}</>
  })

  if (typeof window !== 'undefined') return <>{children}</>

  return (
    <StyleSheetManager sheet={styledComponentsStyleSheet.instance}>
      {children}
    </StyleSheetManager>
  )
}

用样式注册表组件包裹根布局的 children:

TypeScript

app/layout.tsxtsx
import StyledComponentsRegistry from './lib/registry'

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html>
      <body>
        <StyledComponentsRegistry>{children}</StyledComponentsRegistry>
      </body>
    </html>
  )
}

JavaScript

app/layout.jsjsx
import StyledComponentsRegistry from './lib/registry'

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <StyledComponentsRegistry>{children}</StyledComponentsRegistry>
      </body>
    </html>
  )
}

在此查看示例。

须知:

  • 在服务器渲染期间,样式会被提取到全局注册表中,并冲刷到 HTML 的 <head> 中。这确保样式规则位于任何可能使用它们的样式内容之前。将来,我们可能会使用 React 即将推出的某个特性来决定样式的注入位置。
  • 在流式渲染期间,来自每个数据块的样式会被收集并追加到现有样式中。客户端水合完成后,styled-components 会像往常一样接管,并注入后续的任何动态样式。
  • 我们特意在树的顶层使用客户端组件作为样式注册表,因为这样提取 CSS 规则更高效。它可以避免在后续服务器渲染时重新生成样式,并防止这些样式被包含在服务器组件负载中发送。
  • 对于需要配置 styled-components 编译各项属性的高级用例,你可以阅读我们的 Next.js styled-components API 参考 以了解更多信息。