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


当前回答

import React from 'react';

function useTitle(title: string): void => {
  React.useEffect(() => {
    const prevTitle = document.title;
    document.title = title;

    return () => {
      document.title = prevTitle;
    };
  }, []);
}

function MyComponent(): JSX.Element => {
  useTitle('Title while MyComponent is mounted');

  return <div>My Component</div>;
}

这是一个非常直接的解决方案,useTitle设置文档标题,当组件卸载时,它被重置为之前的任何内容。

其他回答

最简单的方法是使用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解决方案-使用Hooks)

创建更改页面标题组件

import React, { useEffect } from "react";

const ChangePageTitle = ({ pageTitle }) => {
  useEffect(() => {
    const prevTitle = document.title;
    document.title = pageTitle;
    return () => {
      document.title = prevTitle;
    };
  });

  return <></>;
};

export default ChangePageTitle;

使用组件

import ChangePageTitle from "../{yourLocation}/ChangePageTitle";

...

return (
    <>
      <ChangePageTitle pageTitle="theTitleYouWant" />
      ...
    </>
  );

...

你应该在'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节点。

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