javascript - 在 ReactJS 中关闭浏览器选项卡时如何触发弹出窗口?

标签 javascript jquery reactjs typescript ecmascript-6

我有一张登记表,其中包含一些与客户相关的信息。如果用户表单已填满一​​半并且用户要关闭选项卡,那么我将触发带有保存和退出选项的弹出窗口,退出。

我有一些 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 库?

谢谢, 丹加杜赖

最佳答案

您可以在 componentDidMount 和 componentWillUnmount 生命周期函数中为“beforeunload”事件添加和删除事件监听器。

https://facebook.github.io/react/docs/component-specs.html

https://developer.mozilla.org/en-US/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;
}
....

关于javascript - 在 ReactJS 中关闭浏览器选项卡时如何触发弹出窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38651020/

相关文章:

javascript - 如何使用 jquery 增加字体大小?

jquery - Angular 2在模板渲染后执行脚本

javascript - 如何将material-ui时间选择器更改为24小时格式

javascript - 如何使用 PHP 从 HTML 获取表单内容?

javascript - firebase - 使用电子邮件和密码创建用户返回未定义的uid

javascript - MySQL 用 PASSWORD() 插入设置

javascript - 表单提交不会停止验证

javascript - 猫头鹰旋转木马销毁问题(未捕获的类型错误 : Cannot read property 'destroy' of undefined )

reactjs - 您如何使用带样式的组件在 React Native 中为 Text 子项设置样式?

reactjs - 创建 React 应用程序 : ESLint config is not working with Typescript