React中点击VIEW BAG按钮需同时执行onClick与页面跳转的求助
解决方案
方法1:通过React Router的history手动跳转(最可靠)
由于你的组件是用connect包裹的类组件,可借助withRouter高阶组件注入history对象,在执行toggleCart后手动触发页面跳转:
- 导入
withRouter:
import { Link, withRouter } from 'react-router-dom'
- 修改组件导出语句,用
withRouter包裹:
export default withRouter(connect(mapStateToProps)(OverlayCartWrapperContainer));
- 移除外层的
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的点击事件:
- 在组件构造函数中新增Ref:
constructor(){ super(); this.state={ ref: React.createRef(null), actionRef: React.createRef(null), } this.cartLinkRef = React.createRef(null); // 新增Ref }
- 修改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
相关产品推荐
相关产品推荐

