自定義文件
自定義 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。
這有幫助嗎?