# next/head

示例

  • Head Elements
  • Layout Component

Next.js 暴露了一个内置组件,用于将 HTML 标签添加到页面的 head中:

import Head from 'next/head'

function IndexPage() {
  return (
    <div>
      <Head>
        <title>My page title</title>
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
      </Head>
      <p>Hello world!</p>
    </div>
  )
}

export default IndexPage

为了避免在 head中出现重复的 HTML 标签,你可以设置 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标签将会被自动处理。

在 unmount 组件时,head中的内容将会被清理,因此请确保每个页面都定义了其所需的所有内容,不要假设其它页面帮你添加任何内容。

titlemeta或任何其它 HTML 标签(例如 script)必须作为 Head元素的 直接子元素存在, 或者被包裹在最多一层 <React.Fragment>或数组中,否则在客户端导航时这些标签无法被正确识别并使用。

We recommend using next/script in your component instead of manually creating a <script>in next/head.

Last Updated: 5/13/2023, 8:55:38 PM