在作项目的时候,有个需求,当表单页面未保存,切到其余页面时须要用户确认跳转。react
按常理来讲,跳转是由react-router-dom
控制的,因此它也应该有阻止跳转的机制,查了api,发现Prompt
这个组件能够作到这个事。将Prompt
放在须要弹窗的页面里,哪里都行,就能够有这个功能。api
<Prompt message={() => isSave ? true : '有修改还没有保存,肯定要离开页面吗?’} />
Prompt
接受两个属性,message
能够是字符串或方法,方法返回true
就顺利跳转,返回字符串就弹窗阻止跳转。还有个属性when
,是boolean
值,true
就是弹窗,false
为顺利跳转。浏览器
但如今的弹窗是浏览器的默认弹窗,很丑。因此咱们须要自定义一下。antd
在react-router-dom
的BrowserRouter
和HashRouter
上有属性getUserConfirmation
能够阻止默认弹窗。react-router
<BrowserRouter getUserConfirmation={getConfirmation} > <App /> </BrowserRouter>
这个属性是一个方法,参数为Prompt
的message
和弹窗取消和确认的回调。这里我直接用的antd的modal组件做为弹窗。dom
const getConfirmation = (message: any, callback: any) => { Modal.confirm({ title: message, onCancel: () => { callback(false); }, onOk: () => { callback(true); } }); };
最后,在过程当中踩了一个坑。就是不能用router
组件。若是你像这样code
<BrowserRouter getUserConfirmation={getConfirmation} > <Router history={history}> <App /> </Router> </BrowserRouter>
那么getUserConfirmation
是不会起做用的。router