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

React中点击VIEW BAG按钮需同时执行onClick与页面跳转的求助

解决方案

方法1:通过React Router的history手动跳转(最可靠)

由于你的组件是用connect包裹的类组件,可借助withRouter高阶组件注入history对象,在执行toggleCart后手动触发页面跳转:

  1. 导入withRouter:
import { Link, withRouter } from 'react-router-dom'
  1. 修改组件导出语句,用withRouter包裹:
export default withRouter(connect(mapStateToProps)(OverlayCartWrapperContainer));
  1. 移除外层的Link组件,直接在按钮的onClick中完成两个操作:
<ActionSection>
  <ViewBagButton onClick={(e) => {
    this.props.toggleCart(e);
    this.props.history.push('/cart');
  }}>VIEW BAG</ViewBagButton>
  <CheckoutButton>CHECKOUT</CheckoutButton>
</ActionSection>

方法2:检查并移除阻止默认行为的代码

如果toggleCart函数内部调用了e.preventDefault(),会直接阻断Link的默认跳转逻辑。找到该函数并移除类似代码:

// 从toggleCart函数中删除此行
e.preventDefault();

之后保留原有的Link包裹结构即可:

<Link to="/cart">
  <ViewBagButton onClick={(e) => this.props.toggleCart(e)}>VIEW BAG</ViewBagButton>
</Link>

方法3:通过Ref手动触发Link跳转

如果上述方法都不适用,可通过Ref直接调用Link的点击事件:

  1. 在组件构造函数中新增Ref:
constructor(){
  super();
  this.state={
    ref: React.createRef(null),
    actionRef: React.createRef(null),
  }
  this.cartLinkRef = React.createRef(null); // 新增Ref
}
  1. 修改JSX结构:
<ActionSection>
  <Link ref={this.cartLinkRef} to="/cart">
    <ViewBagButton onClick={(e) => {
      this.props.toggleCart(e);
      this.cartLinkRef.current.click();
    }}>VIEW BAG</ViewBagButton>
  </Link>
  <CheckoutButton>CHECKOUT</CheckoutButton>
</ActionSection>

内容的提问来源于stack exchange,提问作者sarangkkl

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:06:34