我有一个包含一些与客户有关的信息的登记表。如果用户表单已填充一半,并且用户将关闭选项卡,那么我将触发带有保存和退出,退出选项的弹出窗口。
我有一些jQuery解决方案。但是如今,它并不是在所有浏览器中都能正常工作。
jQuery示例代码:
'use strict';
$(document).ready(function() {
$.fn.addEvent = function (obj, evType, fn) {
if (obj.addEventListener) {
obj.addEventListener(evType, fn, false);
return true;
} else if (obj.attachEvent) {
var r = obj.attachEvent('on'+evType, fn);
return r;
} else {
return false;
}
};
$.fn.KeepOnPage = function (e) {
var doWarn = 1;
if (!e) {
e = window.event;
}
if (!e) {
return;
}
if (doWarn == 1) { // and condition whatever you want to add here
e.cancelBubble = true;
e.returnValue = 'Warning!\n\nNavigating away from this page will delete your text if you haven\'t already saved it.';
}
if (e.stopPropagation) {
e.stopPropagation();
}
};
$.fn.addEvent(window, 'beforeunload', $.fn.KeepOnPage);
});
但是我们需要ReactJS中的解决方案。是否有任何React库可用于浏览器卸载?
谢谢,Thangadurai
您可以在componentDidMount和componentWillUnmount生命周期函数中添加和删除“ beforeunload”事件的事件侦听器。
https://facebook.github.io/react/docs/component-specs.html
https://developer.mozilla.org/zh-CN/docs/Web/Events/beforeunload
例子:
...
componentDidMount() {
window.addEventListener('beforeunload', this.keepOnPage);
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.keepOnPage);
}
keepOnPage(e) {
var message = 'Warning!\n\nNavigating away from this page will delete your text if you haven\'t already saved it.';
e.returnValue = message;
return message;
}
....
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句