首页 > 解决方案 > 如何在 html 中从下一个/头移动到头

问题描述

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

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

但是,如果我将此代码 <Head><title>Page title</title></Head> 放置在 _app.js 或 _document.js 以外的任何位置,则会出现在<body>页面的标记中,这是不需要的。

在此处输入图像描述

// 模块/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>
    )
  }
}

标签: reactjsnext.js

解决方案


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

document.title = 'My New Title';

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


推荐阅读