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 內容,而不要假設其他頁面添加了什麼。

使用最小層級的嵌套

titlemeta 或其他元素(例如 script)必須作為 Head 元件的直接子元素,或最多包覆在一層 <React.Fragment> 或陣列中——否則這些標籤在客戶端導航時可能無法正確被讀取。

使用 next/script 來載入腳本

我們建議在元件中使用 next/script,而不是手動在 next/head 中創建 <script>

不要使用 htmlbody 標籤

不能使用 <Head> 來設定 <html><body> 標籤的屬性。這會導致 next-head-count is missing 錯誤。next/head 只能處理 HTML <head> 標籤內的元素。

On this page