React Router v4.x中点击Link时如何添加确认弹窗再跳转?
解决React Router v4中点击Link前弹出确认模态框的问题
要实现点击<Link>时先弹出确认框,确认后再跳转,核心思路是拦截Link的默认跳转行为,手动触发确认模态框,用户确认后再通过history对象完成跳转。下面是完整的实现方案:
完整代码示例
import { Modal } from 'antd'; import { Link, withRouter } from 'react-router-dom'; import React, { Component } from 'react'; const confirm = Modal.confirm; class Menu extends Component { constructor(props) { super(props); this.handleLinkClick = this.handleLinkClick.bind(this); } handleLinkClick(e, targetPath) { // 阻止Link的默认跳转行为 e.preventDefault(); // 弹出确认模态框 confirm({ title: '确认跳转吗?', content: '你确定要跳转到目标页面吗?', okText: 'YES', cancelText: 'NO', onOk: () => { // 用户确认后,手动调用history跳转 this.props.history.push(targetPath); }, onCancel: () => { // 用户取消,无需额外操作 console.log('用户取消跳转'); } }); } render() { return ( <div className="menu"> {/* 改造Link,绑定自定义点击事件并传入目标路径 */} <Link to="/target-page" onClick={(e) => this.handleLinkClick(e, '/target-page')} > 跳转到目标页面 </Link> </div> ); } } // 用withRouter包裹组件,让它能获取到history对象 export default withRouter(Menu);
关键步骤说明
- 拦截默认行为:在
onClick事件中调用e.preventDefault(),阻断Link自带的跳转逻辑。 - 获取history对象:通过
withRouter高阶组件包裹组件,让组件能从props中拿到history,用于手动触发页面跳转。 - 确认后执行跳转:在Modal的
onOk回调里,调用this.props.history.push(targetPath)完成页面跳转。
注意事项
- 如果你的组件已经是路由直接渲染的子组件(比如通过
<Route component={Menu} />渲染),它会自动接收history、location等props,无需额外用withRouter包裹。 - 可以根据业务需求自定义模态框的标题、提示内容、按钮文字等,适配不同场景。
内容的提问来源于stack exchange,提问作者jhonyoung
相关产品推荐
相关产品推荐

