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;
相关推荐
終不似少年遊*1 天前
【安全业务Agent】从场景到编排
python·react.js·ai·langchain·agent·安全架构·工作流
JavaPub-rodert2 天前
从零搭建通用管理后台:ShiyuAdmin 的 Go、React 与 RBAC 实践
开发语言·react.js·golang
Highcharts.js2 天前
React 中原生支持使用 JSX 组件配置自定义表格 Highcharts Grid
前端·javascript·react.js·前端框架·jsx·highcharts·自定义表格
JudithHuang2 天前
React 嵌套路由与布局
前端·react.js·arcgis·react·react router
前端小D2 天前
React Native项目开发(iOS侧为例)
javascript·react native·react.js
志尊宝3 天前
AI原生前端开发(042):AI辅助的路由设计与优化
javascript·react.js·ai-native
znsoft4 天前
MaClaw(码卡龙)技术拆解:一个 Go + React 的可自进化智能体平台
开发语言·react.js·golang
濮水大叔4 天前
React/Next.js 生态里,有没有 CabloyJS 这样的全栈框架?
react.js·全栈·next.js
前端小D4 天前
React Native Android 项目搭建
android·react native·react.js
Highcharts.js5 天前
Highcharts 集成到 React 或 Vue 项目中时,如何高效地使用 TypeScript技巧?
vue.js·人工智能·react.js·typescript·前端框架·highcharts