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

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

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

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

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

var App = React.createClass({
  render: function () {
    // Use "My Web App" if no child overrides this
    return (
      <DocumentTitle title='My Web App'>
        <this.props.activeRouteHandler />
      </DocumentTitle>
    );
  }
});
 
var HomePage = React.createClass({
  render: function () {
    // Use "Home" while this component is mounted
    return (
      <DocumentTitle title='Home'>
        <h1>Home, sweet home.</h1>
      </DocumentTitle>
    );
  }
});
 
var NewArticlePage = React.createClass({
  mixins: [LinkStateMixin],
 
  render: function () {
    // Update using value from state while this component is mounted
    return (
      <DocumentTitle title={this.state.title || 'Untitled'}>
        <div>
          <h1>New Article</h1>
          <input valueLink={this.linkState('title')} />
        </div>
      </DocumentTitle>
    );
  }
});

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

render{

    return(

         <DocumentTitle>

         ......

         </DocumentTitle>

   )

}

 

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

 



参考资料:

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

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值