您的位置:首页 > Web前端 > React

react-router(v3)切换页面时不刷新页面,实现显示和隐藏子路由组件

2018-04-04 20:32 1281 查看
v4版本应该也差不多的解决方法

思路很简单:就是在{this.props.children}渲染的地方进行处理,根据当前路由名称判断组件显示与隐藏。

children即this.props.children;
将children保存到全局windows中
save = (children) => {
this.routeName = children.props.route.name;
if (!window.routeCache) window.routeCache = {};
if (!window.routeCache[this.path]) window.routeCache[this.path] = {};
if (!window.routeCache[this.path][this.routeName]) {
window.routeCache[this.path][this.routeName] = children;
}
}


然后在{this.props.children}的位置使用下面的方法,判断当前路由选择对应组件进行显示和隐藏
render = () => {
return Object.keys(window.routeCache[this.path]).map((key) => {
if (key === this.routeName) return <div key={key} style={{height: '100%'}}>{window.routeCache[this.path][key]}</div>;
return <div key={key} style={{display: 'none'}}>{window.routeCache[this.path][key]}</div>;
});
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐