我想为我的React应用程序设置文档标题(在浏览器标题栏中)。我尝试使用react-document-title(似乎过时了)和设置文档。在构造函数和componentDidMount()中的title -这些解决方案都不起作用。
当前回答
正如其他人提到的,你可以使用文档。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!
参见:添加自定义环境变量
其他回答
你可以创建TabTittleHelper.js和
export const TabTittle = (newTitle) => {
document.title=newTitle;
return document.title;
};
后来你编写了所有的屏幕
TabTittle('tittleName');
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} />
最简单的方法是使用react-document-configuration
NPM安装react-document-configuration
例子:
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 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>
)
}
它将在组件挂载时立即更新标题,并在卸载时将其恢复到以前的标题。
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