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中所需的内容,而不要假设其他页面添加了什么。
使用最小嵌套
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> 标签内的标签。
这有帮助吗?