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


当前回答

如果你想知道,你可以直接在渲染函数中设置它:

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

class App extends React.Component {
    render() {
        document.title = 'wow'
        return <p>Hello</p>
    }
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
)

对于功能组件:

function App() {
    document.title = 'wow'
    return <p>Hello</p>
}

但是,这是一个不好的做法,因为它会阻塞渲染(React优先考虑渲染)。

好的做法:

类组件:

class App extends React.Component {
    // you can also use componentDidUpdate() if the title is not static
    componentDidMount(){
        document.title = "good"
    }

    render() {
        return <p>Hello</p>
    }
}

功能组件:

function App() {
    // for static title, pass an empty array as the second argument
    // for dynamic title, put the dynamic values inside the array
    // see: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
    useEffect(() => {
        document.title = 'good'
    }, []);

    return <p>Hello</p>
}

其他回答

对于React 16.8+,你可以在函数组件中使用Effect Hook:

import React, { useEffect } from 'react';

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

要以声明的方式管理所有有效的头部标签,包括<title>,你可以使用React Helmet组件:

import React from 'react';
import { Helmet } from 'react-helmet';

const TITLE = 'My Page Title';

class MyComponent extends React.PureComponent {
  render () {
    return (
      <>
        <Helmet>
          <title>{ TITLE }</title>
        </Helmet>
        ...
      </>
    )
  }
}

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

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

钩子的更新:

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

你可以创建TabTittleHelper.js和

export const TabTittle = (newTitle) => {
document.title=newTitle;
return document.title;
};

后来你编写了所有的屏幕

TabTittle('tittleName');

对于这个问题,你有多种选择,我强烈建议使用React Helmet或使用useEffect创建钩子。除了编写自己的钩子,你还可以使用react-use中的钩子:

反应的头盔

import React from 'react';
import { Helmet } from 'react-helmet';

const MyComponent => () => (
  <Helmet>
    <title>My Title</title>
  </Helmet>
)

react-use

import React from 'react';
import { useTitle } from 'react-use';

const MyComponent = () => {
  useTitle('My Title');

  return null;
}