自定义文档
自定义 Document 可以更新用于渲染 页面 的 <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>
)
}须知:
_document仅在服务器上渲染,因此不能在此文件中使用onClick等事件处理程序。<Html>、<Head />、<Main />和<NextScript />是页面正确渲染所必需的。
注意事项
_document中使用的<Head />组件与next/head不同。这里使用的<Head />组件应该只用于所有页面通用的任何<head>代码。对于所有其他情况,例如<title>标签,我们建议在您的页面或组件中使用next/head。<Main />之外的 React 组件不会被浏览器初始化。不要在此处添加应用程序逻辑或自定义 CSS(例如styled-jsx)。如果您需要在所有页面中共享组件(例如菜单或工具栏),请阅读 布局。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
// Run the React rendering logic synchronously
ctx.renderPage = () =>
originalRenderPage({
// Useful for wrapping the whole react tree
enhanceApp: (App) => App,
// Useful for wrapping in a per-page basis
enhanceComponent: (Component) => Component,
})
// Run the parent `getInitialProps`, it now includes the custom `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。
这有帮助吗?