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 nedenleonClick
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
_document
adresinde kullanılan<Head />
bileşeni, aşağıdaki bileşenlerle aynı değildirnext/head
. Burada kullanılan<Head />
bileşeni yalnızca tüm sayfalar için ortak olan<head>
kodu için kullanılmalıdır.<title>
etiketleri gibi diğer tüm durumlar için şunları kullanmanızı öneririznext/head
sayfalarınızda veya bileşenlerinizde.<Main />
dışındaki React bileşenleri tarayıcı tarafından başlatılmayacaktır. Buraya uygulama mantığı veya özel CSS eklemeyin (styled-jsx
gibi). Tüm sayfalarınızda paylaşılan bileşenlere ihtiyacınız varsa (bir menü veya araç çubuğu gibi), bunun yerine Düzenleri okuyun.Document
gibi Next.js Veri Getirme yöntemlerini şu anda desteklemiyorgetStaticProps
veyagetServerSideProps
.
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çinctx
nesnesi şu adreste alınana eşdeğerdirgetInitialProps
ile birlikterenderPage
.