在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>)}
})