服装企业营销网站建设,简单的wordpress主题,手机网站源码带后台,北京共振设计公司官网一 基本介绍
作用#xff1a; 把不是通过路由切换过来的组件中#xff0c;将react-router 的 history、location、match 三个对象传入props对象上。比如首页#xff01; 默认情况下必须是经过路由匹配渲染的组件才存在this.props#xff0c;才拥有路由参数#xff0c;才能…一 基本介绍
作用 把不是通过路由切换过来的组件中将react-router 的 history、location、match 三个对象传入props对象上。比如首页 默认情况下必须是经过路由匹配渲染的组件才存在this.props才拥有路由参数才能使用编程式导航的写法执行this.props.history.push(‘/detail’)跳转到对应路由的页面 然而不是所有组件都直接与路由相连通过路由跳转到此组件的当这些组件需要路由参数时使用withRouter就可以给此组件传入路由参数此时就可以使用this.props 二 withRouter使用
import React from react;
import {withRouter} from ../react-router-dom;
class NavHeader extends React.Component{render(){return div onClick{()this.props.history.push(/)}{this.props.title}/div}
}export default withRouter(NavHeader);三 withRouter源码实现
import React from react;
import RouterContext from ./RouterContext;
function withRouter(OldComponent){return props(RouterContext.Consumer{(value)(OldComponent {...value} {...props}/)}/RouterContext.Consumer)
}
export default withRouter;