react中实现路由切换时离开页面确认d窗提示

react中实现路由切换时离开页面确认d窗提示,第1张

d窗前确认

一、需要离开提示页面上添加

a.引入Prompt

b.在页面中添加组件,可在render内任一地方添加

<Prompt message='商家信息还未保存,是否离开?' when={true} />

二、在路由页面进行配置

a.Router上添加 getUserConfirmation={getConfirmation}

b.在路由页面添加方法

三、触发d窗

通过设置window.pageChangeConfirm,触发是否d窗。

例:在componentDidMount设置默认离开是否d窗。 也可在点击页面时触发修改d窗参数

第一种是用户进入页面的时候表单为空(例如发表新评论),用户离开的时候有可能表单为空,则不提示,表单有改变但未保存,则提示。实例如下:

<html>

<meta http-equiv="Content-Type" content="text/htmlcharset=utf-8" />

<head>

<script type="text/javascript">

function checkNew() {

var content = document.getElementById("content").value

if(content !== "") {

return "内容已改变,点击“取消”保存表单。"

}

}

window.onbeforeunload = checkNew

</script>

</head>

<body>

<form>

<textarea cols="50" rows="10" id="content"></textarea>

</form>

</body>

</html>

第二种是用户进入页面的时候表单不为空(例如编辑评论),用户离开的时候有可能表单内容没有改变,则不提示,表单和进入页面的时候内容有差异但未保存,则提示。实例如下:

<html>

<meta http-equiv="Content-Type" content="text/htmlcharset=utf-8" />

<head>

<script type="text/javascript">

var originalContent

window.onload = getOriginal

function getOriginal() {

originalContent = document.getElementById("content").value

}

function checkEdit() {

var newContent = document.getElementById('content').value

if(newContent !== originalContent) {

return "内容已改变,点击“取消”保存表单。"

}

}

window.onbeforeunload = checkEdit

</script>

</head>

<body>

<form>

<textarea cols="50" rows="10" id="content">原始内容,原始内容,原始内容,原始内容</textarea>

</form>

</body>

</html>

================

我给出的例子是最基本的框架,其它例如提示信息,如何保存等还要进一步优化。

例子中使用的编码为 utf-8,注意保存时使用相同编码以免出现乱码。

离开页面确认主要是利用了onbeforeunload事件,当该事件声明为

<body onbeforeunload="return pageBeforeunload(event)">

时(注意是return一个函数),在页面离开时将d出默认的询问确认窗口, pageBeforeunload()函数只需要返回一个字符串,字符串的内容将显示在该窗口的中间一行,点击OK离开页面,点击Cancel继续停留在当前页面。

该方式具体的代码如下:

<script type="text/javascript">var curElementfunction pageBeforeunload(evt){return 'Are you sure you want to leave this page?'}</script>    <body onbeforeunload="return pageBeforeunload(event)">    </body>

另外一种方式是把onbeforeunload声明为:

在该种方式下,将不会d出系统默认的离开确认对话框,此时可以在pageBeforeunload函数内部,通过调用confirm方法进行确认,这种方式的好处是,即便在用户确认离开页面的时候,也可以进行必要的状态保存 *** 作。此时pageBeforeunload的代码可以写成:

function pageBeforeunload(evt){var confirm = confirm('Are you sure to leave this page?')if(confirm == true){// 添加必要的处理逻辑   }}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11882218.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存