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。
参考资料:
https://www.npmjs.com/package/react-document-title
https://www.jianshu.com/p/07ed93350483
还没有评论,来说两句吧...