React

react 根据路由动态改变页面title

2017-12-13  本文已影响12人  Evan_zhan

当然可以自己写,实现方式也很简单。在切换路由的时候去改变document.title就可以了

因为在ant design pro的项目中看到,使用了github上'react-document-title' 的这个组件,就了解了一下~

根据不同路由,更改页面title

方式:

1.引入

    import DocumentTitle from 'react-document-title';
  1. render函数顶层

     <DocumentTitle title={this.getPageTitle()}>
           <div></div>
     </DocumentTitle>
    

3.getPageTitle函数 根据当前路由更改对应的title

  getPageTitle() {
    const { location, getRouteData } = this.props;
    const { pathname } = location;
    let title = 'Ant Design Pro';
    getRouteData('BasicLayout').forEach((item) => {
      if (item.path === pathname) {
        title = `${item.name} - Ant Design Pro`;
      }
    });
    return title;
  }

至此 大功告成

github地址:https://github.com/gaearon/react-document-title

上一篇 下一篇

猜你喜欢

热点阅读