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


当前回答

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

其他回答

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设置文档标题,当组件卸载时,它被重置为之前的任何内容。

你可以使用下面的文档。title = '主页'

import React from 'react'
import { Component } from 'react-dom'


class App extends Component{
  componentDidMount(){
    document.title = "Home Page"
  }

  render(){
    return(
      <p> Title is now equal to Home Page </p>
    )
  }
}

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

或者你可以使用这个npm包npm i react-document-title

import React from 'react'
import { Component } from 'react-dom'
import DocumentTitle from 'react-document-title';


class App extends Component{


  render(){
    return(
      <DocumentTitle title='Home'>
        <h1>Home, sweet home.</h1>
      </DocumentTitle>
    )
  }
}

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

编码快乐! !

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

document.title="Page Title";

你可以使用ReactDOM和修改<title>标签

ReactDOM.render(
   "New Title",
   document.getElementsByTagName("title")[0]
);

正如其他人提到的,你可以使用文档。title = 'My new title'和React Helmet来更新页面标题。这两个解决方案仍然会在脚本加载之前呈现初始的“React App”标题。

如果你使用的是create-react-app,初始文档标题设置在<title>标签/public/index.html文件中。

你可以直接编辑它,或者使用一个占位符来填充环境变量:

/.环境:

REACT_APP_SITE_TITLE='My Title!'
SOME_OTHER_VARS=...

如果出于某种原因,我想在我的开发环境中使用不同的标题—

/ .env.development:

REACT_APP_SITE_TITLE='**DEVELOPMENT** My TITLE! **DEVELOPMENT**'
SOME_OTHER_VARS=...

/公共/ index . html:

<!DOCTYPE html>
<html lang="en">
    <head>
         ...
         <title>%REACT_APP_SITE_TITLE%</title>
         ...
     </head>
     <body>
         ...
     </body>
</html>

这种方法还意味着我可以使用全局流程从应用程序读取站点标题环境变量。Env对象,这很好

console.log(process.env.REACT_APP_SITE_TITLE_URL);
// My Title!

参见:添加自定义环境变量