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


当前回答

你应该在'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 16.8开始。你可以构建一个自定义钩子来实现(类似于@Shortchange的解决方案):

export function useTitle(title) {
  useEffect(() => {
    const prevTitle = document.title
    document.title = title
    return () => {
      document.title = prevTitle
    }
  })
}

这可以在任何react组件中使用,例如:

const MyComponent = () => {
  useTitle("New Title")
  return (
    <div>
     ...
    </div>
  )
}

它将在组件挂载时立即更新标题,并在卸载时将其恢复到以前的标题。

我不确定这是否是一个好的做法,但在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

const [name, setName] = useState("Jan");
  useEffect(() => 
    {document.title =   "Celebrate " +  {name}.name  ;}
  );