我想为我的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>
)
}
它将在组件挂载时立即更新标题,并在卸载时将其恢复到以前的标题。
其他回答
你可以使用ReactDOM和修改<title>标签
ReactDOM.render(
"New Title",
document.getElementsByTagName("title")[0]
);
你可以简单地在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
你可以使用下面的文档。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')
);
编码快乐! !
你应该在'componentWillMount'的生命周期中设置文档标题:
componentWillMount() {
document.title = 'your title name'
},
钩子的更新:
useEffect(() => {
document.title = 'current Page Title';
}, []);
对于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 };
也适用于动态页面,只需传递产品标题或任何您想要显示的内容。