美文网首页
react-withRouter 用法

react-withRouter 用法

作者: 云高风轻 | 来源:发表于2023-04-25 11:43 被阅读0次

1. 前言

  1. react-router-dom 5x版本 里面 还是有 withRouter
  2. 简单说下用法

2. withRouter 功能

  1. 把不是通过路由切换过来的组件中,将react-router 的 history、location、match 三个对象传入props对象上
  2. 用法也非常简单 就是把组件 作为withRouter() 的从参数就行

3. 相关代码

import React from "react";
import { withRouter } from "react-router-dom";

 function PlayCom(props) {
  console.log("子组件-props", props);

  return (
    <div className="box">
      <div className="my-title">子组件</div>
      <button onClick={() => {
         props.history.push("/");
      }}> 跳转</button>
    </div>
  );
}
//  正常导出 不具备 路由/BOM 功能
// export default PlayCom;

// 高阶函数 参数是组件的函数
//  高阶组件 让我们 的组件 具备 更多的功能

// withRouter 自动注入 BOM 相关 API
export default withRouter(PlayCom);
//子组件默认 不具备 路由相关的 API
//  route 配置 的时候
// 会自动给 路由页面 注入 相关 API


5. 延伸一个路由传参方式

  1. 相关代码
  2. 也可以在路由配置的时候 传递参数
         {/*  自己注入内容 / 扩展功能 高阶函数  
          // 形参默认就是路由对象/BOM
          / r  routeProps
          */}
            <Route  exact path="/blog/ios"  render={(routeProps)=>{
              // 父子组件传参
              // return <IosPage name={r}/>
              return <IosPage {...routeProps}  salary="18k" />

            }} />
  1. 如果不传递 从传递routeProps/形参
  2. 当前这个页面 其实也不具备 history、location、match 三个对象

参考资料


初心

我所有的文章都只是基于入门,初步的了解;是自己的知识体系梳理,如有错误,道友们一起沟通交流;
如果能帮助到有缘人,非常的荣幸,一切为了部落的崛起;
共勉

相关文章

网友评论

      本文标题:react-withRouter 用法

      本文链接:https://www.haomeiwen.com/subject/npapjdtx.html