利用Prompt,阻止react路由切换,弹窗确认,而且自定义弹窗样式

在作项目的时候,有个需求,当表单页面未保存,切到其余页面时须要用户确认跳转。react

按常理来讲,跳转是由react-router-dom控制的,因此它也应该有阻止跳转的机制,查了api,发现Prompt这个组件能够作到这个事。将Prompt放在须要弹窗的页面里,哪里都行,就能够有这个功能。api

<Prompt message={() => isSave ? true : '有修改还没有保存,肯定要离开页面吗?’} />

Prompt接受两个属性,message能够是字符串或方法,方法返回true就顺利跳转,返回字符串就弹窗阻止跳转。还有个属性when,是boolean值,true就是弹窗,false为顺利跳转。浏览器

但如今的弹窗是浏览器的默认弹窗,很丑。因此咱们须要自定义一下。antd

react-router-domBrowserRouterHashRouter上有属性getUserConfirmation能够阻止默认弹窗。react-router

<BrowserRouter getUserConfirmation={getConfirmation} >
        <App />
    </BrowserRouter>

这个属性是一个方法,参数为Promptmessage和弹窗取消和确认的回调。这里我直接用的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

相关文章
相关标签/搜索