Javascript 你如何在 React 中设置文档标题?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46160461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you set the document title in React?
提问by eli
I would like to set the document title (in the browser title bar) for my React application. I have tried using react-document-title(seems out of date) and setting document.titlein the constructorand componentDidMount()- none of these solutions work.
我想为我的 React 应用程序设置文档标题(在浏览器标题栏中)。我已经尝试使用反应文档标题(似乎过时了),并设置document.title在constructor与componentDidMount()这些解决方案的工作- 。
采纳答案by quotesBro
You can use React Helmet:
您可以使用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>
...
</>
)
}
}
回答by AlexVestin
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')
);
This works for me.
这对我有用。
Edit: If you're using webpack-dev-server set inline to true
编辑:如果您使用 webpack-dev-server 设置 inline 为 true
回答by Jordan Daniels
For React 16.8, you can do this with a functional component using useEffect.
对于 React 16.8,您可以使用useEffect使用功能组件执行此操作。
For Example:
例如:
useEffect(() => {
document.title = "new title"
}, []);
Having the second argument as an array calls useEffect only once, making it similar to componentDidMount.
将第二个参数作为数组只调用一次 useEffect,使其类似于componentDidMount.
回答by Gruffy
As others have mentioned, you can use document.title = 'My new title'and React Helmetto update the page title. Both of these solutions will still render the initial 'React App' title before scripts are loaded.
正如其他人所说,你可以使用document.title = 'My new title'并作出反应头盔更新页面标题。这两种解决方案仍将在加载脚本之前呈现初始的“React App”标题。
If you are using create-react-appthe initialdocument title is set in the <title>tag /public/index.htmlfile.
如果使用的create-react-app是初始文档标题,则在<title>标记/public/index.html文件中设置。
You can edit this directly or use a placeholder which will be filled from environmental variables:
您可以直接编辑它或使用将从环境变量填充的占位符:
/.env:
/.env:
REACT_APP_SITE_TITLE='My Title!'
SOME_OTHER_VARS=...
If for some reason I wanted a different title in my development environment -
如果出于某种原因我想在我的开发环境中使用不同的标题 -
/.env.development:
/.env.development:
REACT_APP_SITE_TITLE='**DEVELOPMENT** My TITLE! **DEVELOPMENT**'
SOME_OTHER_VARS=...
/public/index.html:
/public/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
...
<title>%REACT_APP_SITE_TITLE%</title>
...
</head>
<body>
...
</body>
</html>
This approach also means that I can read the site title environmental variable from my application using the global process.envobject, which is nice:
这种方法还意味着我可以使用全局process.env对象从我的应用程序中读取站点标题环境变量,这很好:
console.log(process.env.REACT_APP_SITE_TITLE_URL);
// My Title!
See: Adding Custom Environment Variables
请参阅:添加自定义环境变量
回答by Alvin
you should set document title in the life cycle of 'componentWillMount':
您应该在“componentWillMount”的生命周期中设置文档标题:
componentWillMount() {
document.title = 'your title name'
},
回答by Colonel Thirty Two
React Portalscan let you render to elements outside the root React node (such at <title>), as if they were actual React nodes. So now you can set the title cleanly and without any additional dependencies:
React Portals可以让你渲染根 React 节点(例如<title>)之外的元素,就好像它们是实际的 React 节点一样。所以现在你可以干净地设置标题并且没有任何额外的依赖:
Here's an example:
下面是一个例子:
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;
Just put the component in the page and set pageTitle:
只需将组件放入页面并设置pageTitle:
<Title pageTitle="Dashboard" />
<Title pageTitle={item.name} />
回答by amin msh
Simply you can create a function in a js file and export it for usages in components
简单地,您可以在 js 文件中创建一个函数并将其导出以在组件中使用
like below:
像下面这样:
export default function setTitle(title) {
if (typeof title !== "string") {
throw new Error("Title should be an string");
}
document.title = title;
}
and use it in any component like this:
并在任何组件中使用它,如下所示:
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
回答by mpen
I haven't tested this too thoroughly, but this seems to work. Written in TypeScript.
我还没有对此进行过彻底的测试,但这似乎有效。用 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;
}
}
Usage:
用法:
export default class App extends React.Component<Props, State> {
render() {
return <>
<DocumentTitle>{this.state.files.length} Gallery</DocumentTitle>
<Container>
Lorem ipsum
</Container>
</>
}
}
Not sure why others are keen on putting their entire app insidetheir <Title>component, that seems weird to me.
不知道为什么其他人热衷于将他们的整个应用程序放在他们的<Title>组件中,这对我来说似乎很奇怪。
By updating the document.titleinside render()it'll refresh/stay up to date if you want a dynamic title. It should revert the title when unmounted too. Portals are cute, but seem unnecessary; we don't really need to manipulate any DOM nodes here.
如果您想要动态标题,通过更新document.title内部,render()它将刷新/保持最新。它也应该在卸载时恢复标题。门户很可爱,但似乎没有必要;我们真的不需要在这里操作任何 DOM 节点。
回答by EsterlingAccime Youtuber
You can use the following below with document.title = 'Home Page'
您可以将以下内容与 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')
);
or You can use this npm package npm i react-document-title
或者你可以使用这个 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')
);
Happy Coding!!!
编码快乐!!!
回答by reza moradi
You can use ReactDOM and altering <title>tag
你可以使用 ReactDOM 和改变<title>标签
ReactDOM.render(
"New Title",
document.getElementsByTagName("title")[0]
);

