javascript 如何设置每页文档的标题?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52170634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:51:28  来源:igfitidea点击:

How to set document's title per page?

javascriptreactjsnext.js

提问by acmoune

I am actually using the pages/_document.jshook to add Bootstrapand jQueryto my pages, by the way I set the <Head>

我实际上是使用pages/_document.js钩子来添加Bootstrap和添加jQuery到我的页面中<Head>

export default class MyDocument extends Document {
  render() {
    return (
      <html>
        <Head>
          <title>Default title</title>
          <link rel="stylesheet" href="/static/lib/bootstrap3/css/bootstrap.min.css" />
        </Head>

        <body>
          <Main/>
          <NextScript/>
          <script src="/static/lib/jquery3/jquery-3.3.1.min.js" />
          <script src="/static/lib/bootstrap3/js/bootstrap.min.js" />
        </body>
      </html>
    )
  }
}

Now I would like to set a different Title,for my pages. Is it possible to used <Head>outside of Document? I mean in <div>like this:

现在我想为我的页面设置一个不同的标题。可以在<Head>外面使用Document吗?我的意思<div>是这样:

const ContactPage = () => {
  return (
    <div>
      <Head>
        <title>You better contact us!</title>
      </Head>

      <div className="page-body">...</div>
    </div>
  )
}

And if possible, will it overwrite or merge what is already set in pages/_document.js?

如果可能,它会覆盖或合并已经设置的内容pages/_document.js吗?

回答by Jeff Kilbride

You want to use the next/headcomponent:

您要使用的next/head组件:

import Head from 'next/head'

export default () =>
  <div>
    <Head>
      <title>My page title</title>
      <meta name="viewport" content="initial-scale=1.0, width=device-width" />
    </Head>

    <p>Hello world!</p>
  </div>

See the docs: https://nextjs.org/docs/#populating-head

查看文档:https: //nextjs.org/docs/#populating-head

updated link: https://nextjs.org/docs/api-reference/next/head

更新链接:https: //nextjs.org/docs/api-reference/next/head