React-document-title实现动态更新页面Title

Bertha 。 2022-12-11 07:52 277阅读 0赞

因为react是单页应用,所以可能需要根据不同的路由改变文档的title。

我们可以使用react-document-title组件实现,其提供了一种document.title在单页面应用程序中指定的声明方式。

首先使用 npm install react-document-title 进行安装,然后在文件中引入 import DocumentTitle from “react-document-title”

官方文档提供了以下几种例子:

  1. var App = React.createClass({
  2. render: function () {
  3. // Use "My Web App" if no child overrides this
  4. return (
  5. <DocumentTitle title='My Web App'>
  6. <this.props.activeRouteHandler />
  7. </DocumentTitle>
  8. );
  9. }
  10. });
  11. var HomePage = React.createClass({
  12. render: function () {
  13. // Use "Home" while this component is mounted
  14. return (
  15. <DocumentTitle title='Home'>
  16. <h1>Home, sweet home.</h1>
  17. </DocumentTitle>
  18. );
  19. }
  20. });
  21. var NewArticlePage = React.createClass({
  22. mixins: [LinkStateMixin],
  23. render: function () {
  24. // Update using value from state while this component is mounted
  25. return (
  26. <DocumentTitle title={this.state.title || 'Untitled'}>
  27. <div>
  28. <h1>New Article</h1>
  29. <input valueLink={this.linkState('title')} />
  30. </div>
  31. </DocumentTitle>
  32. );
  33. }
  34. });

我在实现各页面动态显示title时,在各自文件render的return返回里,最外层使用DocumentTitle组件。

render{

  1. return(
  2. <DocumentTitle>
  3. ......
  4. </DocumentTitle>

)

}

然后,对其title属性可以定义想要现实的标题。这样,当点击切换到指定的页面时,就会动态变化title。

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzIzMTMzNzgz_size_16_color_FFFFFF_t_70

参考资料:

  1. https://www.npmjs.com/package/react-document-title

  2. https://www.jianshu.com/p/07ed93350483

发表评论

表情:
评论列表 (有 0 条评论,277人围观)

还没有评论,来说两句吧...

相关阅读