在React中更改文档标题?

fns*_*jdb 18 dom reactjs

我正在尝试在React应用程序中更新文档的标题.我对此有非常简单的需求.Total即使您在不同的选项卡上,标题也主要用于显示组件.

这是我的第一直觉:

const React = require('react');

export default class Total extends React.Component {
  shouldComponentUpdate(nextProps) {
    //otherstuff
    document.title = this.props.total.toString();
    console.log("Document title: ", document.title);
    return true;
  }
  render() {
    document.title = this.props.total;
    return (
      <div className="text-center">
        <h1>{this.props.total}</h1>
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我认为这只会在document.title每次渲染此组件时更新,但它似乎没有做任何事情.

不知道我在这里缺少什么.可能与React如何运行此函数有关 - 可能是某个document变量不可用的地方?

编辑:

我正在为这个问题开始赏金,因为我还没有找到任何解决方案.我已将代码更新为更新版本.

一个奇怪的发展是,console.log 打印出来我正在寻找的称号.但由于某种原因,选项卡中的实际标题不会更新.此问题在Chrome,Safari和Firefox中都是相同的.

Bal*_*zar 11

我现在为此目的使用react-helmet,因为它允许自定义不同的元标记和链接,并且它还支持SSR.

import { Helmet } from 'react-helmet'

const Total = () => (
  <div className="text-center">
    <Helmet>
      <meta charSet="utf-8" />
      <title>{this.props.total}</title>
    </Helmet>
    <h1>{this.props.total}</h1>
  </div>
)
Run Code Online (Sandbox Code Playgroud)

原始答案:为此目的,gaeron 实际上有一个,但是以声明的方式:

import React, { Component } from 'react'
import DocumentTitle from 'react-document-title'

export default class Total extends Component {

  render () {
    return (
      <DocumentTitle title={this.props.total}>
        <div className='text-center'>
          <h1>{this.props.total}</h1>
        </div>
      </DocumentTitle>
    )
  }

}
Run Code Online (Sandbox Code Playgroud)


mew*_*ewc 10

里面的componentDidMount()函数 App.js(或地方),只是有:

componentDidMount() {
    document.title = "Amazing Page";
}
Run Code Online (Sandbox Code Playgroud)

这样做的原因是在你的 React 项目中的任何地方你都可以访问 Js 全局范围。继续并输入window您的站点控制台。基本上你可以在 React 项目中访问的所有内容。


Jed*_*rds 7

我认为webpack-dev-server默认情况下以iframe模式运行:

https://webpack.github.io/docs/webpack-dev-server.html#iframe-mode

这可能就是为什么你设置标题的尝试都失败了.如果您还没有,请尝试将该inline选项设置为true webpack-dev-server.


ros*_*dia 5

如果该react-document-title软件包对您不起作用,则可以通过生命周期方法(可能同时使用componentDidMount和)进行快速操作,这很肮脏componentWillReceiveProps(您可以在此处了解更多信息):

因此,您将执行以下操作:

const React = require('react');

export default class Total extends React.Component {

  // gets called whenever new props are assigned to the component
  // but NOT during the initial mount/render
  componentWillReceiveProps(nextProps) {
    document.title = this.props.total;
  }

  // gets called during the initial mount/render
  componentDidMount() {
    document.title = this.props.total;
  }

  render() {    
    return (
      <div className="text-center">
        <h1>{this.props.total}</h1>
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)