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


当前回答

从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>
  )
}

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

其他回答

正如其他人提到的,你可以使用文档。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!

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

如果你是一个初学者,你可以去你的react项目文件夹的公共文件夹,在“index.html”中编辑标题,然后把你的标题放进去。别忘了保存,这样照片才会反射。

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

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

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

对于这个问题,你有多种选择,我强烈建议使用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;
}