自定义 Document
自定义 Document
可以更新用于渲染页面的 <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>
)
}
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,它可以更轻松地为页面和布局获取数据。
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
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
。