【问题标题】:How can I move <Head> from next/head from body to head in the html如何在 html 中将 <Head> 从 next/head 从 body 移动到 head
【发布时间】:2019-05-15 21:53:24
【问题描述】:

我需要为页面的&lt;title&gt;&lt;/title&gt; 添加动态值。为此,我正在使用 next/head 提供的 Head 组件。

标题需要在某些用户操作时更改(因此不能放在 _app.js 或 _document.js 中)。

但是,如果我放置此代码: &lt;Head&gt;&lt;title&gt;Page title&lt;/title&gt;&lt;/Head&gt; _app.js 或 _document.js 以外的任何地方,都会出现在页面的 &lt;body&gt; 标记中,这是不需要的。

// 模块/about_us/index.js

import Head from 'next/head'

export default class AboutUs extends Component {
  state = {
    title: 'About you'
  }
  someEvent1(){
    this.setState({title : 'About team'})
  }
  someEvent2(){
    this.setState({title : 'About company'})
  }
  render(){
    return (
      <div>
        <Head>
          <title>{this.state.title}</title>
        </Head>
        <div>This is one of the module used to display the page.</div>
        <button onClick={this.someEvent1}>About team</button>
        <button onClick={this.someEvent2}>About company</button>
      </div>
    )
  }
}

【问题讨论】:

  • 你找到答案了吗?
  • 也遇到这种情况

标签: reactjs next.js


【解决方案1】:

我建议使用纯 javascript 而不是尝试通过 jsx / 标记来调整它。

document.title = 'My New Title';

https://developer.mozilla.org/en-US/docs/Web/API/Document/title

【讨论】:

  • 试过了,还是一样的问题。
  • 有什么问题?标题将出现在浏览器标题栏中。
【解决方案2】:

您可以为此使用 react-helmet

来自自述文件:

import React from "react";
import {Helmet} from "react-helmet";

class Application extends React.Component {
  render () {
    return (
        <div className="application">
            <Helmet>
                <meta charSet="utf-8" />
                <title>My Title</title>
                <link rel="canonical" href="http://example.com" />
            </Helmet>
            ...
        </div>
    );
  }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    • 2019-11-25
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多