我想为我的React应用程序设置文档标题(在浏览器标题栏中)。我尝试使用react-document-title(似乎过时了)和设置文档。在构造函数和componentDidMount()中的title -这些解决方案都不起作用。


当前回答

我不确定这是否是一个好的做法,但在index.js头我放:

document.title="Page Title";

其他回答

import React from 'react'
import ReactDOM from 'react-dom'


class Doc extends React.Component{
  componentDidMount(){
    document.title = "dfsdfsdfsd"
  }

  render(){
    return(
      <b> test </b>
    )
  }
}

ReactDOM.render(
  <Doc />,
  document.getElementById('container')
);

这对我很有用。

编辑:如果你使用webpack-dev-server,将内联设置为true

你应该在'componentWillMount'的生命周期中设置文档标题:

componentWillMount() {
    document.title = 'your title name'
  },

钩子的更新:

useEffect(() => {
    document.title = 'current Page Title';
  }, []);

我还没有对它进行彻底的测试,但这似乎是可行的。用TypeScript编写。

interface Props {
    children: string|number|Array<string|number>,
}

export default class DocumentTitle extends React.Component<Props> {

    private oldTitle: string = document.title;

    componentWillUnmount(): void {
        document.title = this.oldTitle;
    }

    render() {
        document.title = Array.isArray(this.props.children) ? this.props.children.join('') : this.props.children;
        return null;
    }
}

用法:

export default class App extends React.Component<Props, State> {

    render() {
        return <>
            <DocumentTitle>{this.state.files.length} Gallery</DocumentTitle>
            <Container>
                Lorem ipsum
            </Container>
        </>
    }
}

不知道为什么其他人热衷于将整个应用程序放在<Title>组件中,这对我来说似乎很奇怪。

通过更新文档。如果你想要一个动态标题,render()内的标题会刷新/保持最新。卸载时也应该恢复标题。传送门很可爱,但似乎没有必要;我们不需要操作任何DOM节点。

你可以简单地在js文件中创建一个函数,并将其导出到组件中使用

像下图:

export default function setTitle(title) {
  if (typeof title !== "string") {
     throw new Error("Title should be an string");
  }
  document.title = title;
}

并像这样在任何组件中使用它:

import React, { Component } from 'react';
import setTitle from './setTitle.js' // no need to js extension at the end

class App extends Component {
  componentDidMount() {
    setTitle("i am a new title");
  }

  render() {
    return (
      <div>
        see the title
      </div>
    );
  }
}

export default App

对于React v18+,自定义钩子将是最简单的方法。

步骤1:创建钩子。(钩/ useDocumentTitle.js)

import { useEffect } from "react";
export const useDocumentTitle = (title) => {

    useEffect(() => {
        document.title = `${title} - WebsiteName`;
    }, [title]);

    return null;
}

步骤2:在每个具有自定义标题的页面上调用钩子。(页面/ HomePage.js)

import { useDocumentTitle } from "../hooks/useDocumentTitle";

const HomePage = () => {
    useDocumentTitle("Website Title For Home Page");
    
    return (
        <>           
            <main>
                <section>Example Text</section>
            </main>            
        </>
    );
}

export { HomePage };

也适用于动态页面,只需传递产品标题或任何您想要显示的内容。