Head
我們公開了一個內建元件,用於將元素附加到頁面的 head
import Head from 'next/head'
function IndexPage() {
return (
<div>
<Head>
<title>My page title</title>
</Head>
<p>Hello world!</p>
</div>
)
}
export default IndexPage
避免重複的標籤
為了避免在您的 head
中出現重複的標籤,您可以使用 key
屬性,這將確保標籤只渲染一次,如下例所示
import Head from 'next/head'
function IndexPage() {
return (
<div>
<Head>
<title>My page title</title>
<meta property="og:title" content="My page title" key="title" />
</Head>
<Head>
<meta property="og:title" content="My new title" key="title" />
</Head>
<p>Hello world!</p>
</div>
)
}
export default IndexPage
在這種情況下,只會渲染第二個 <meta property="og:title" />
。具有重複 key
屬性的 meta
標籤會自動處理。
小知識:Next.js 會自動檢查
<title>
和<base>
標籤是否重複,因此這些標籤不需要使用 key。
head
的內容會在卸載元件時清除,因此請確保每個頁面都完整定義了head
中需要的內容,而不要假設其他頁面新增了什麼。
使用最少的巢狀結構
title
、meta
或任何其他元素(例如 script
)需要包含為 Head
元素的直接子元素,或最多包裝成一層 <React.Fragment>
或陣列—否則,標籤在用戶端導航時將無法正確擷取。
針對腳本使用 next/script
我們建議在您的元件中使用 next/script
,而不是在 next/head
中手動建立 <script>
。
沒有 html
或 body
標籤
您不能使用 <Head>
來設定 <html>
或 <body>
標籤上的屬性。這將導致 next-head-count is missing
錯誤。next/head
只能處理 HTML <head>
標籤內的標籤。
這有幫助嗎?