标头
Examples
我们公开一个内置组件,用于将元素附加到页面的 head
:
¥We expose a built-in component for appending elements to the head
of the page:
import Head from 'next/head'
function IndexPage() {
return (
<div>
<Head>
<title>My page title</title>
</Head>
<p>Hello world!</p>
</div>
)
}
export default IndexPage
避免重复标签
¥Avoid duplicated tags
为了避免 head
中出现重复标记,你可以使用 key
属性,这将确保标记仅渲染一次,如下例所示:
¥To avoid duplicate tags in your head
you can use the key
property, which will make sure the tag is only rendered once, as in the following example:
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
标签会被自动处理。
¥In this case only the second <meta property="og:title" />
is rendered. meta
tags with duplicate key
attributes are automatically handled.
很高兴知道:Next.js 会自动检查
<title>
和<base>
标签是否重复,因此这些标签不需要使用 key。¥Good to know:
<title>
and<base>
tags are automatically checked for duplicates by Next.js, so using key is not necessary for these tags.
卸载组件后,
head
的内容会被清除,因此请确保每个页面完全定义了head
中所需的内容,而无需假设其他页面添加的内容。¥The contents of
head
get cleared upon unmounting the component, so make sure each page completely defines what it needs inhead
, without making assumptions about what other pages added.
使用最小嵌套
¥Use minimal nesting
title
、meta
或任何其他元素(例如 script
)需要作为 Head
元素的直接子元素包含在内,或者封装到最多一级的 <React.Fragment>
或数组中,否则将无法在客户端导航上正确拾取标签。
¥title
, meta
or any other elements (e.g. script
) need to be contained as direct children of the Head
element,
or wrapped into maximum one level of <React.Fragment>
or arrays—otherwise the tags won't be correctly picked up on client-side navigations.
使用 next/script
作为脚本
¥Use next/script
for scripts
我们建议在你的组件中使用 next/script
,而不是在 next/head
中手动创建 <script>
。
¥We recommend using next/script
in your component instead of manually creating a <script>
in next/head
.
没有 html
或 body
标签
¥No html
or body
tags
你不能使用 <Head>
设置 <html>
或 <body>
标签的属性。这将导致 next-head-count is missing
错误。next/head
只能处理 HTML <head>
标记内的标记。
¥You cannot use <Head>
to set attributes on <html>
or <body>
tags. This will result in an next-head-count is missing
error. next/head
can only handle tags inside the HTML <head>
tag.