我想为我的React应用程序设置文档标题(在浏览器标题栏中)。我尝试使用react-document-title(似乎过时了)和设置文档。在构造函数和componentDidMount()中的title -这些解决方案都不起作用。
当前回答
我不确定这是否是一个好的做法,但在index.js头我放:
document.title="Page Title";
其他回答
我想使用页面标题我的常见问题页面。所以我用了反应头盔。
首先,我用npm i react-helmet安装了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 ) } }
你可以使用ReactDOM和修改<title>标签
ReactDOM.render(
"New Title",
document.getElementsByTagName("title")[0]
);
我不确定这是否是一个好的做法,但在index.js头我放:
document.title="Page 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>
}