我有一个简单的react-component,用户可以在其中编辑数据。由于可能更改的值可能会花费一些时间,因此我想请用户确认是否在未保存更改的情况下离开页面。
在组件的构造函数中,我调用:
window.addEventListener("beforeunload", this.handleWindowBeforeUnload);
Run Code Online (Sandbox Code Playgroud)
我也试过
window.onbeforeunload = this.handleWindowBeforeUnload;
Run Code Online (Sandbox Code Playgroud)
该handleWindowBeforeUnload如下所示:
private handleWindowBeforeUnload = (ev: BeforeUnloadEvent): string => {
return "Unsaved changes. Are you sure?";
}
Run Code Online (Sandbox Code Playgroud)
但是,设置断点会命中。但是,没有任何迹象表明离开可能是危险的。也尝试使用最新的Firefox,但没有任何反应。如MDN所述,我也尝试过
// Cancel the event as stated by the standard.
e.preventDefault();
// Chrome requires returnValue to be set.
e.returnValue = '';
// return something to trigger a dialog
return null; // ''; // "Do something"
Run Code Online (Sandbox Code Playgroud)
仍然没有任何反应。我在这里做错了什么?