已解决
封装withRouter并且使用
来自网友在路上 158858提问 提问时间:2023-10-26 08:24:48阅读次数: 58
最佳答案 问答题库588位专家为你答疑解惑
在react后续的版本中,路由组件中props找不到router相关的方法,这就需要自己去封装一个withRouter插件,给路由组件的props上配置原来的属性,方便路由组件中进行路由操作.
代码如下:
新建一个withRouter.jsx文件
import {useLocation,useNavigate,useParams,} from "react-router-dom";function withRouter(Component) {function ComponentWithRouterProp(props) {let location = useLocation();let navigate = useNavigate();let params = useParams();return (<Component{...props}router={{ location, navigate, params }}/>);}return ComponentWithRouterProp;}export default withRouter
使用如下
import React, { Component } from 'react'
import {Routes,Route} from 'react-router-dom'import { Button } from 'antd';
import withRouter from '../../utils/withRouter'
export default withRouter(class index extends Component {jumpLogin = ()=>{//操作props中router内的属性方法,就可以操作路由了this.props.router.navigate('/login')}render() {console.log(this.props,'路由')return (<div><h2>dashborad页面</h2><div className='dashboardContent'><Button type='primary' onClick={this.jumpLogin}>跳转到登录页面</Button></div></div>)}
})
查看全文
99%的人还看了
相似问题
猜你感兴趣
版权申明
本文"封装withRouter并且使用":http://eshow365.cn/6-24921-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!