NNext.js 中文网 GitHub

如何使用 CSS-in-JS 库

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

警告: 将 CSS-in-JS 与 Server Component、Streaming 等较新的 React 特性一起使用,需要库作者支持最新版本的 React,包括并发渲染。

以下库在 app 目录的 Client Component 中受支持(按字母顺序):

以下库目前正在适配支持:

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

在 app 中配置 CSS-in-JS#

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

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

styled-jsx#

在 Client Component 中使用 styled-jsx 需要使用 v5.1.0。首先,创建一个新的注册表:

app/registry.tsx
'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
}) {
  // 仅使用惰性初始状态创建一次样式表
  // 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>
}
app/registry.js
'use client'

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

export default function StyledJsxRegistry({ children }) {
  // 仅使用惰性初始状态创建一次样式表
  // 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>
}

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

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

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html>
      <body>
        <StyledJsxRegistry>{children}</StyledJsxRegistry>
      </body>
    </html>
  )
}
app/layout.js
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.js
module.exports = {
  compiler: {
    styledComponents: true,
  },
}

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

lib/registry.tsx
'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
}) {
  // 仅使用惰性初始状态创建一次样式表
  // 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>
  )
}
lib/registry.js
'use client'

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

export default function StyledComponentsRegistry({ children }) {
  // 仅使用惰性初始状态创建一次样式表
  // 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:

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

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html>
      <body>
        <StyledComponentsRegistry>{children}</StyledComponentsRegistry>
      </body>
    </html>
  )
}
app/layout.js
import StyledComponentsRegistry from './lib/registry'

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

在此查看示例。

小知识:

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

<details> <summary>示例</summary>

</details>

可以使用任何现有的 CSS-in-JS 方案。最简单的是内联样式:

jsx
function HiThere() {
  return <p style={{ color: 'red' }}>hi there</p>
}

export default HiThere

我们内置了 styled-jsx,以提供对隔离作用域 CSS 的支持。 目标是支持类似 Web Components 的"shadow CSS",但遗憾的是 Web Components不支持服务端渲染,且只能使用 JS。

其他流行的 CSS-in-JS 方案(如 Styled Components)请参阅上面的示例。

使用 styled-jsx 的组件如下所示:

jsx
function HelloWorld() {
  return (
    <div>
      Hello world
      <p>scoped!</p>
      <style jsx>{`
        p {
          color: blue;
        }
        div {
          background: red;
        }
        @media (max-width: 600px) {
          div {
            background: blue;
          }
        }
      `}</style>
      <style global jsx>{`
        body {
          background: black;
        }
      `}</style>
    </div>
  )
}

export default HelloWorld

更多示例请参阅 styled-jsx 文档。

禁用 JavaScript#

是的,即使禁用 JavaScript,在生产构建(next start)中 CSS 仍会被加载。在开发期间,我们要求启用 JavaScript,以通过 Fast Refresh 提供最佳的开发者体验。

Next.js 中文网