如何在React中设置文档标题?

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

276280 次浏览
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

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

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

钩子的更新:

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

对于React 16.8+,你可以在函数组件中使用影响钩:

import React, { useEffect } from 'react';


function Example() {
useEffect(() => {
document.title = 'My Page Title';
}, []);
}
< p >
要以声明的方式管理所有有效的头标记,包括<title>,你可以使用反应的头盔组件:

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>
...
</>
)
}
}

你可以对document.title = 'Home Page'使用下面的方法

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')
);

编码快乐! !

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

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

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

/.env:

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

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

/.env.development:

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

/public/index.html:

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

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

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

看:添加自定义环境变量

React 门户网站可以让你渲染根React节点(比如<title>)之外的元素,就像它们是实际的React节点一样。所以现在你可以干净地设置标题,没有任何额外的依赖:

这里有一个例子:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';


class Title extends Component {
constructor(props) {
super(props);
this.titleEl = document.getElementsByTagName("title")[0];
}


render() {
let fullTitle;
if(this.props.pageTitle) {
fullTitle = this.props.pageTitle + " - " + this.props.siteTitle;
} else {
fullTitle = this.props.siteTitle;
}


return ReactDOM.createPortal(
fullTitle || "",
this.titleEl
);
}
}
Title.defaultProps = {
pageTitle: null,
siteTitle: "Your Site Name Here",
};


export default Title;

只需将组件放入页面并设置pageTitle:

<Title pageTitle="Dashboard" />
<Title pageTitle={item.name} />

我还没有对它进行彻底的测试,但这似乎是可行的。用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()中的document.title,它会刷新/保持最新。卸载时也应该恢复标题。传送门很可爱,但似乎没有必要;我们不需要操作任何DOM节点。

你可以简单地在js文件中创建一个函数,并将其导出到组件中使用

像下图:

export default function setTitle(title) {
if (typeof title !== "string") {
throw new Error("Title should be an string");
}
document.title = title;
}

并像这样在任何组件中使用它:

import React, { Component } from 'react';
import setTitle from './setTitle.js' // no need to js extension at the end


class App extends Component {
componentDidMount() {
setTitle("i am a new title");
}


render() {
return (
<div>
see the title
</div>
);
}
}


export default App

对于React 16.8,你可以使用useEffect的函数组件来做到这一点。

例如:

useEffect(() => {
document.title = "new title"
}, []);

将第二个参数作为数组只调用useEffect一次,使其类似于componentDidMount

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

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

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

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

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

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

最简单的方法是使用react-document-configuration

npm install react-document-configuration --save

例子:

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 Helmet或使用useEffect创建钩子。除了编写自己的钩子,你也可以使用react-use中的钩子:

React头盔

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;
}
const [name, setName] = useState("Jan");
useEffect(() =>
{document.title =   "Celebrate " +  {name}.name  ;}
);
  

我想使用页面标题我的常见问题页面。所以我用了反应头盔。

首先,我使用NPM我反应头盔安装了react-helmet

然后我在我的返回中添加了这样的标签:

import React from 'react'
import { Helmet } from 'react-helmet'
const PAGE_TITLE = 'FAQ page'
export default class FAQ extends Component {
render () {
return (
{ PAGE_TITLE } This is my faq page

) } }
头盔确实是一个很好的方法,但对于那些只需要改变标题的应用程序,这是我使用的: (现代的React解决方案-使用Hooks)

  1. 创建更改页面标题组件
import React, { useEffect } from "react";


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


return <></>;
};


export default ChangePageTitle;
  1. 使用组件
import ChangePageTitle from "../{yourLocation}/ChangePageTitle";


...


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


...

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

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

你可以创建TabTittleHelper.js和

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

后来你编写了所有的屏幕

TabTittle('tittleName');