Custom Document

Özel bir Document, bir Sayfayı oluşturmak için kullanılan <html> ve <body> etiketlerini güncelleyebilir.

Varsayılan Document adresini geçersiz kılmak için, aşağıda gösterildiği gibi pages/_document dosyasını oluşturun:

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>
  )
}

Bildiğim iyi oldu

  • _document yalnızca sunucuda işlenir, bu nedenle onClick gibi olay işleyicileri bu dosyada kullanılamaz.
  • <Html>, <Head />, <Main /> ve <NextScript /> sayfanın düzgün bir şekilde işlenmesi için gereklidir.

Caveats

Customizing renderPage

renderPage adresinin özelleştirilmesi ileri düzeydedir ve yalnızca CSS-in-JS gibi kütüphanelerin sunucu tarafı görüntülemeyi desteklemesi için gereklidir. Bu, yerleşik styled-jsx desteği için gerekli değildir.

Bu kalıbı kullanmanızı önermiyoruz. Bunun yerine, sayfalar ve düzenler için daha kolay veri almanızı sağlayan App Router'ı aşamalı olarak benimsemeyi düşünün.

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

Bildiğim iyi oldu

  • getInitialProps _document adresinde istemci tarafı geçişler sırasında çağrılmaz.
  • _document için ctx nesnesi şu adreste alınana eşdeğerdir getInitialPropsile birlikte renderPage.