行业知识
React withRouter的使用及源码实现
2026-10-30 05:20:43
来源:互联网转载
一 基本介绍
作���: 把不是通过路由切换过来的组件中,将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 ()=this.props.history.push('/')}>{this.props.title} }}export default withRouter(NavHeader); 三 withRouter源码实现
import React from 'react';import RouterContext from './RouterContext';function withRouter(OldComponent){ return props=>( { (value)=>( ...value} {...props}/ ) } )}export default withRouter;
上一篇:网易服务器怎么加好友?