React withRouter的使用及源码实现

一 基本介绍

作用: 把不是通过路由切换过来的组件中,将react-router 的 history、location、match 三个对象传入props对象上。比如首页!

默认情况下必须是经过路由匹配渲染的组件才存在this.props,才拥有路由参数,才能使用编程式导航的写法,执行this.props.history.push('/detail')跳转到对应路由的页面

然而不是所有组件都直接与路由相连(通过路由跳转到此组件)的,当这些组件需要路由参数时,使用withRouter就可以给此组件传入路由参数,此时就可以使用this.props

二 withRouter使用

bash 复制代码
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源码实现

bash 复制代码
import React from 'react';
import RouterContext from './RouterContext';
function withRouter(OldComponent){
  return props=>(
    <RouterContext.Consumer>
        {
            (value)=>(
                <OldComponent {...value} {...props}/>
            )
        }
    </RouterContext.Consumer>
  )
}
export default withRouter;
相关推荐
CaffeinePro15 小时前
告别知识点零散!React零基础通关,从环境搭建到Ant Design页面实战
前端·react.js
Ruihong2 天前
Vue withDefaults 转 React:VuReact 怎么处理?
vue.js·react.js·面试
用户298698530142 天前
在 React 中使用 JavaScript 将 Excel 转换为 SVG
前端·javascript·react.js
小林攻城狮3 天前
使用 Transport 节流解决 Vercel AI SDK 流式渲染卡死问题
前端·react.js
前端缘梦3 天前
告别 TS 运行时类型漏洞!Zod 完整入门实战教程(前端 / 全栈必备)
前端·react.js·全栈
张元清3 天前
React useIntersectionObserver Hook:懒加载与可见性检测(2026)
javascript·react.js
用户298698530143 天前
在 React 中使用 JavaScript 将 Excel 转换为 PDF
javascript·react.js·webassembly
木木剑光3 天前
我开源了一个 React 组件库,沉淀了多个高频组件和实用 Hooks
前端·javascript·react.js
Csvn3 天前
React 19 `use()` 来了:以后数据加载可以不用 useEffect?
前端·react.js