You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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高阶组件,你可以自行封装一个高阶组件注入路由相关方法即可:

  1. 先封装自定义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;
}
  1. 在你的类组件中使用封装好的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 20:45:09