你可以在 NextJS 中添加多个 'HEAD' 元素吗?

Can you have multiple, additive 'HEAD' elements in NextJS?

我希望能够在 _document.js 中有一个 'master' HEAD 元素,并且对于某些页面有一个额外的 HEAD 元素 添加 到 'master' 中的内容。从 https://nextjs.org/docs/api-reference/next/head 看来,这是可能的。

然而,在Stack Overflow中搜索答案时,我发现了this post,这似乎表明这可能会导致意想不到的结果。

如果我不能有多个 HEAD 元素,我是否需要通过 getInitialProps 从单个页面传递数据?

当你需要用它做一些事情时,你可以简单地将 next/head 导入任何 page/component

示例:

import Head from 'next/head'

function IndexPage() {
  return (
    <div>
      <Head>
        <title>My page title</title>
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
      </Head>
      <p>Hello world!</p>
    </div>
  )
}

export default IndexPage

并且在 _document.js

内还有一个默认的 Head
import Document, { Head, Main, NextScript } from 'next/document';

export default class MyDocument extends Document {
  render() {
    return (
      <html lang="en">
        <Head>
          <link rel="shortcut icon" href="/favicon.ico" />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    );
  }
}

到目前为止我没有遇到任何问题。

不过要记住一些事情:

head 的内容在卸载组件时会被清除,因此请确保每个页面都完整地定义了它在 head 中需要的内容,而不要假设其他页面添加了什么。