react-router 在路由切换时进行提示

react-router 版本 ^5.1.2

在有正在编辑的内容未保存时,发生了路由切换,此时需要给出一些提示,并由用户控制是否进行跳转。

react-router进行路由管理时,可以使用 Prompt 组件实现此功能,其中的message属性可以接受一个函数,返回string的时候就提示,默认为window.confirm进行提示,用户可以选择是否跳转;返回true的时候就直接路由切换,不进行提示。

可以将Prompt进行简单的封装,如下:

import { Prompt} from "react-router-dom";

export default function RouterPrompt ({message,promptBoolean}) {
    // Will be called with the next location and action the user is attempting to navigate to. Return a string to show a prompt to the user or true to allow the transition.
    return  <Prompt message={
                        location =>
                            !promptBoolean
                            ? true
                            : message || '当前页面有未保存的内容,是否离开?'
                    }
            />
}

使用的时候,哪个组件需要在离开时进行提示,引入一下就行,可以放在组件的任意位置。是否需要提示由使用者自己控制。

            <div className="hardware">
                {/* 这里是根据输入框的编辑状态来设置是否需要提示 */}
                <RouterPrompt promptBoolean={EDIT_STATUS}></RouterPrompt>
                {/* 其他内容 */}
            </div>

提示默认使用的是window.confirm,但还可以通过getUserConfirmation进行自定义。

import { HashRouter as Router} from "react-router-dom";
import { Modal} from 'antd';

// message 就是window.confirm的message,通过callback控制是否通过
// 这里直接使用antd的Modal组件
customConfirm = (message,callback) => {
    Modal.confirm({
        title:message,
        onCancel: () => {
            callback(false);
            },
            onOk: () => {
            callback(true);
            }
    })
}
<Router getUserConfirmation={customConfirm}></Router>

效果如下:

posted @ 2020-03-25 15:28  Shapeying  阅读(1879)  评论(0编辑  收藏  举报