在 app/pages/_document.tsx
中的 Document
组件可以用于增强应用的
<html>
和 <body>
标签。这是必须的,因为 Blitz 页会跳过周围文档标记的定
义。
默认的 _document.tsx
文件像这样:
import {
Document,
Html,
DocumentHead,
Main,
BlitzScript /*DocumentContext*/,
} from "blitz"
class MyDocument extends Document {
// 只有当你需要自定义这个行为时取消注释
// static async getInitialProps(ctx: DocumentContext) {
// const initialProps = await Document.getInitialProps(ctx)
// return {...initialProps}
// }
render() {
return (
<Html lang="en">
<DocumentHead />
<body>
<Main />
<BlitzScript />
</body>
</Html>
)
}
}
export default MyDocument
要正确地渲染页面,必须使用
<Html>
、<DocumentHead />
、<Main />
和<BlitzScript />
。
自定义属性是被允许作为 props 的,比如 lang
:
<Html lang="en">
ctx
参数是一个包含以下键的对象:
pathname
- 当前路线。是在 /pages 中的文件路径。req
:
HTTP IncomingMessage 对象。res
:
HTTP response 对象。err
- 渲染期间遇到任何错误的错误对象。renderPage
: Function
- 一个回调,它实际运行 React 渲染逻辑(同步)。
装饰此功能以支持诸如 styled-components 之类的服务端渲染包装器会很有用。Document
仅在服务端渲染,像 onClick
之类的事件处理器将不起作用。<Main />
之外的 React 组件不会被浏览器初始化。不要 在此处添加应用
逻辑。如果你需要在所有页面中共享组件(例如菜单和工具栏),请参考
App
组件。Document
的 getInitialProps
函数。ctx.req
/ ctx.res
是否已经定义在了 getInitialProps
。通过
自动静态优化 静态导出页面时,这
些变量将为 undefined
。<Head />
标签中添加 <title>
。应该避免在
app/pages/_document.js
中使用,因为这会导致意外的行为。renderPage
应该注意的是,你要自定义
renderPage
的唯一原因是与 css-in-js 库配 合使用,这些库需要将应用包装以正确地与服务端渲染一起使用。
它使用一个 options 对象作为进一步定制的参数:
import { Document } from "blitz"
class MyDocument extends Document {
static async getInitialProps(ctx) {
const originalRenderPage = ctx.renderPage
ctx.renderPage = () =>
originalRenderPage({
// 对包裹整个 React 树很有用
enhanceApp: (App) => App,
// 对于包裹每页基础很有用
enhanceComponent: (Component) => Component,
})
// Run the parent `getInitialProps`, it now includes the custom `renderPage`
const initialProps = await Document.getInitialProps(ctx)
return initialProps
}
}
export default MyDocument