这是实现提示的效果哦~
首先须要依赖这个这个插件 react-router-navigation-prompt
下面是具体的代码react
import React from 'react'; import { Modal, } from 'antd'; import NavigationPrompt from 'react-router-navigation-prompt'; const confirm = Modal.confirm; class RouterAlert extends React.Component { // 设置当前路由切换时是否切换 可根据具体业务操做 state = { isWhen: false, }; render() { const { isWhen } = this.state; return ( <div> /** * @param crntLocation 当前路由路径数据 * @param nextLocation 要切换的路由路径数据 * pathname 表明路径的值 * * */ <NavigationPrompt when={(crntLocation, nextLocation) => { if (isWhen && crntLocation.pathname !== nextLocation.pathname) { return true; } return false; } } > /** * @param onConfirm 肯定离开调用当前函数 * @param onCancel 不离开时调用当前函数 * * */ {({ onConfirm, onCancel }) => { confirm({ title: '检测到您还有数据未保存,肯定离开吗?', onOk() { onConfirm(); }, onCancel() { onCancel(); }, }); }} </NavigationPrompt> </div> ); } }
好了~ 这个效果就实现了。npm