当前位置: 移动技术网 > IT编程>开发语言>JavaScript > react-router 在路由切换时进行提示

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

2020年03月26日  | 移动技术网IT编程  | 我要评论

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>

效果如下:

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网