自訂 Document
自訂 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
。
這有幫助嗎?