<Head>
我们提供了一个内置组件,用于向页面的 head 追加元素:
import Head from 'next/head'
function IndexPage() {
return (
<div>
<Head>
<title>我的页面标题</title>
</Head>
<p>Hello world!</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>Hello world!</p>
</div>
)
}
export default IndexPage在这个例子中,只有第二个 <meta property="og:title" /> 会被渲染。带有重复 key 属性的 meta 标签会被自动处理。
head中的内容会在组件卸载时被清除,因此请确保每个页面完整定义其所需的head内容,不要对其他页面添加的内容做假设。
title、meta 或其他元素(如 script)必须作为 Head 元素的直接子元素,或者最多包裹在一层 <React.Fragment> 或数组中——否则这些标签在客户端导航时无法被正确识别。
我们建议在组件中使用 next/script 而不是手动在
next/head中创建<script>。