如何在HTML中从下一个/头部从身体移到头部

时间:2019-05-15 21:53:25

标签: reactjs next.js

我需要为页面的<title></title>添加动态值。我正在使用由next / head提供的Head组件。

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

但是,如果我放置以下代码: <Head><title>Page title</title></Head> _app.js或_document.js之外的其他任何地方,该页面的<body>标记中都会出现,这是不希望的。

enter image description here

// modules / 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>
    )
  }
}

2 个答案:

答案 0 :(得分:1)

我建议您使用纯JavaScript,而不是尝试通过jsx /标记对其进行调整。

document.title = 'My New Title';

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

答案 1 :(得分:0)

您可以为此使用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>
    );
  }
};
相关问题