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


当前回答

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

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

钩子的更新:

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

其他回答

React门户可以让你渲染根React节点之外的元素(比如<title>),就像它们是实际的React节点一样。所以现在你可以干净地设置标题,没有任何额外的依赖:

这里有一个例子:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Title extends Component {
    constructor(props) {
        super(props);
        this.titleEl = document.getElementsByTagName("title")[0];
    }

    render() {
        let fullTitle;
        if(this.props.pageTitle) {
            fullTitle = this.props.pageTitle + " - " + this.props.siteTitle;
        } else {
            fullTitle = this.props.siteTitle;
        }

        return ReactDOM.createPortal(
            fullTitle || "",
            this.titleEl
        );
    }
}
Title.defaultProps = {
    pageTitle: null,
    siteTitle: "Your Site Name Here",
};

export default Title;

只需将组件放在页面中并设置pageTitle:

<Title pageTitle="Dashboard" />
<Title pageTitle={item.name} />

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

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

钩子的更新:

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

最简单的方法是使用react-document-configuration

NPM安装react-document-configuration

例子:

import React from "react";
import Head from "react-document-configuration";

export default function Application() {
    return (
        <div>
            <Head title="HOME" icon="link_of_icon" />
            <div>
                <h4>Hello Developers!</h4>
            </div>
        </div>
    );
};```

对于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 };

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

我想使用页面标题我的常见问题页面。所以我用了反应头盔。

首先,我用npm i react-helmet安装了react-helmet

然后我在我的返回中添加了这样的标签:

import React from 'react'
import { Helmet } from 'react-helmet'
const PAGE_TITLE = 'FAQ page'
export default class FAQ extends Component {
render () {
return (
{ PAGE_TITLE } This is my faq page ) } }