1

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

任何帮助都会有所帮助和赞赏。

    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);
4

1 回答 1

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);
于 2020-01-23T12:43:15.087 回答