我在React中有两个“静态”页面:“关于”和“条款和条件”。他们没有任何国家或道具。
在显示这些页面时,呈现document.title
的最佳方法是什么?
我正在使用功能无状态组件,所以没有componentDidMount
。
export default function About() {
return (<article>
<h1>About us</h1>
<p>Lorem ipsum dolor sit amet</p>
</div>
</article>);
}
在一个网站上建议在返回声明之前使用document.title = "About"
,如下所示。由于功能组件可以被认为具有隐式render()
和render()
应该是纯函数(它不与浏览器交互),而不是最佳解决方案。
export default function About() {
document.title = "About";
return (<article>
<h1>About us</h1>
<p>Lorem ipsum dolor sit amet</p>
</div>
</article>);
}
是否有意义使用另一个使用<WindowTitle title="About" />
来修改窗口标题的类组件componentDidMount
,并在功能组件中使用该组件?还是有更好的解决方案?
class WindowTitle extends Component() {
constructor(props) {
super(props)
}
componentDidMount() {
document.title = this.props.title;
}
}
function About() {
return (<article>
<WindowTitle title="About" />
<h1>About us</h1>
<p>Lorem ipsum dolor sit amet</p>
</div>
</article>);
}
在html的头部添加标签的方法之一是使用react-helmet包。它还允许添加其他头标记。
<Helmet>
<meta charSet="utf-8" />
<title>My Title</title>
<link rel="canonical" href="" />
</Helmet>