自定义 Document
扩展 Next.js 添加的默认 document 标记。
自定义 Document 可以更新用于渲染 Page 的 <html> 和 <body> 标签。
要覆盖默认的 Document,请按如下所示创建 pages/_document 文件:
pages/_document.tsx
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}pages/_document.jsx
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 的数据获取方法,例如getStaticProps或getServerSideProps。
自定义 renderPage#
自定义 renderPage 属于高级用法,只有 CSS-in-JS 之类的库才需要它来支持服务端渲染。内置的 styled-jsx 支持不需要这样做。
我们不建议使用这种模式。 相反,请考虑逐步采用 App Router,它让你可以更轻松地为页面和布局获取数据。
pages/_document.tsx
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 MyDocumentpages/_document.jsx
import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document {
static async getInitialProps(ctx) {
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在客户端切换时不会被调用。_document的ctx对象与getInitialProps中接收到的对象相同,只是多了renderPage。