自訂文件
自訂的 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` 支援不需要這樣做。
**我們不建議使用這種模式。** 建議考慮逐步採用應用程式路由器,它可以讓您更輕鬆地為頁面和佈局擷取資料。
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`。
這有幫助嗎?