Head
我们提供了一个内置组件,用于在页面的 head
中添加元素:
import Head from 'next/head'
function IndexPage() {
return (
<div>
<Head>
<title>我的页面标题</title>
</Head>
<p>你好,世界!</p>
</div>
)
}
export default IndexPage
避免重复标签
为避免在 head
中出现重复标签,你可以使用 key
属性,这将确保标签只被渲染一次,如下例所示:
import Head from 'next/head'
function IndexPage() {
return (
<div>
<Head>
<title>我的页面标题</title>
<meta property="og:title" content="我的页面标题" key="title" />
</Head>
<Head>
<meta property="og:title" content="我的新标题" key="title" />
</Head>
<p>你好,世界!</p>
</div>
)
}
export default IndexPage
在这种情况下,只会渲染第二个 <meta property="og:title" />
。具有重复 key
属性的 meta
标签会被自动处理。
值得注意的是:
<title>
和<base>
标签会被 Next.js 自动检查重复性,因此对这些标签使用 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>
标签内的标签。