跳到内容

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 标签会被自动处理。

须知: <title><base> 标签会被 Next.js 自动检查重复项,因此对于这些标签,没有必要使用 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> 标签内的标签。