自定义文档 (Custom Document)

自定义 Document 可用于更新渲染 页面 (Page) 时使用的 <html><body> 标签。

要覆盖默认的 Document,请按照以下方式创建 pages/_document 文件:

import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
  return (
    <Html lang="en">
      <Head />
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}

须知

  • _document 仅在服务端渲染,因此不能在此文件中使用诸如 onClick 之类的事件处理程序。
  • <Html><Head /><Main /><NextScript /> 是页面正确渲染所必需的组件。

注意事项

  • _document 中使用的 <Head /> 组件与 next/head 不同。此处的 <Head /> 应仅用于所有页面共有的 <head> 代码。对于其他情况(如 <title> 标签),建议在页面或组件中使用 next/head
  • <Main /> 之外的 React 组件不会被浏览器初始化。请勿在此处添加应用逻辑或自定义 CSS(如 styled-jsx)。如果需要在所有页面中共享组件(如菜单或工具栏),请参阅 布局 (Layouts)
  • Document 目前不支持 Next.js 的 数据获取方法 (Data Fetching methods),如 getStaticPropsgetServerSideProps

自定义 renderPage

自定义 renderPage 属于高级用法,仅适用于需要服务端渲染支持的库(如 CSS-in-JS)。内置的 styled-jsx 不需要此操作。

我们不推荐使用此模式。 建议考虑 逐步采用 (incrementally adopting) App Router,它可以更轻松地为 页面和布局 (pages and layouts) 获取数据。

import Document, {
  Html,
  Head,
  Main,
  NextScript,
  DocumentContext,
  DocumentInitialProps,
} from 'next/document'

class MyDocument extends Document {
  static async getInitialProps(
    ctx: DocumentContext
  ): Promise<DocumentInitialProps> {
    const originalRenderPage = ctx.renderPage

    // 同步运行 React 渲染逻辑
    ctx.renderPage = () =>
      originalRenderPage({
        // 用于包装整个 React 树
        enhanceApp: (App) => App,
        // 用于按页面包装
        enhanceComponent: (Component) => Component,
      })

    // 运行父级的 `getInitialProps`,现在包含自定义的 `renderPage`
    const initialProps = await Document.getInitialProps(ctx)

    return initialProps
  }

  render() {
    return (
      <Html lang="en">
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

须知

  • _document 中的 getInitialProps 在客户端跳转时不会被调用。
  • _documentctx 对象与 getInitialProps 中接收的对象相同,但增加了 renderPage 属性。

On this page