【问题标题】:How to show alert while closing the react application in browser tab [duplicate]如何在浏览器选项卡中关闭反应应用程序时显示警报[重复]
【发布时间】:2020-01-23 12:11:39
【问题描述】:

当我们从浏览器选项卡关闭 React 应用程序时,我尝试了下面的代码来显示警报,但它没有发生,它在没有警报的情况下关闭。 我也尝试过其他有用的帖子,但对我没有任何帮助。

任何帮助都会有所帮助和感激。

    import React from "react";
    import ReactDOM from "react-dom";

    class App extends React.Component {
      onUnload = e => {
        e.preventDefault();
        alert("hi");
      };

      componentDidMount() {
        window.addEventListener("beforeunload", this.onUnload);
      }

      render() {
        return "Alok"
      }
    }

    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);

【问题讨论】:

  • 将unload定义为普通类函数unLoad(e) { ... }就像render和componentDidMount一样。

标签: reactjs react-redux browser-close


【解决方案1】:

尝试创建全局函数handleGloablListeners并在beforeunload事件内部处理; 例如:

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  onUnload = (e) => {
    event.returnValue = 'Are you sure you want to leave?';
  };
  componentDidMount() {
    window.addEventListener('beforeunload', this.onUnload);
  }
  render() {
    return "Alok"
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

【讨论】:

    猜你喜欢
    • 2021-11-25
    • 2018-12-12
    • 2019-12-24
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 2021-07-13
    相关资源
    最近更新 更多