react下路由切换 询问提示

  • 在业务场景中,某些页面(页面生成的数据离开页面未保存)时须要提示操做者是否确认离开当前页面,若是用系统的提示的信息不免有点太丑,显得和页面样式格格不入。*
    下面是我用react版本结合antd的实现 须要的同窗能够参考下哈

这是实现提示的效果哦~
clipboard.png
首先须要依赖这个这个插件 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

相关文章
相关标签/搜索