React类组件中如何通过点击按钮实现路由跳转?
React Class Component 路由跳转实现方案
你可以根据你使用的React Router版本选择对应实现方案:
版本为React Router v5
- 从
react-router-dom引入withRouter高阶组件,用它包裹你的类组件后,组件props会被注入history对象,直接调用对应的跳转方法即可 - 注意:如果你需要先执行自定义逻辑再跳转,无需在外层嵌套
<Link>,避免出现跳转逻辑冲突
代码示例:
import React, { Component } from 'react'; import { withRouter } from 'react-router-dom'; class YourComponent extends Component { nextBtn = () => { // 此处写你需要执行的其他逻辑 // ... // 执行路由跳转,跳转到对应Display组件的路由路径 this.props.history.push('/display'); } render() { return ( <button onClick={this.nextBtn} className="nextBtn"> Submit </button> ) } } // 用withRouter包裹组件后导出 export default withRouter(YourComponent);
版本为React Router v6
v6版本官方移除了withRouter高阶组件,你可以自行封装一个高阶组件注入路由相关方法即可:
- 先封装自定义withRouter高阶组件
import { useNavigate, useLocation, useParams } from 'react-router-dom'; function withRouter(Component) { function ComponentWithRouterProp(props) { const location = useLocation(); const navigate = useNavigate(); const params = useParams(); return ( <Component {...props} router={{ location, navigate, params }} /> ); } return ComponentWithRouterProp; }
- 在你的类组件中使用封装好的withRouter
class YourComponent extends Component { nextBtn = () => { // 此处写你需要执行的其他逻辑 // ... // 执行路由跳转 this.props.router.navigate('/display'); } render() { return ( <button onClick={this.nextBtn} className="nextBtn"> Submit </button> ) } } export default withRouter(YourComponent);
也可以选择直接从父级函数组件中把navigate方法作为props传入类组件使用,无需额外封装高阶组件。
内容的提问来源于stack exchange,提问作者Boom
相关产品推荐
相关产品推荐

