相关疑难解决方法(0)

onbeforeunload在React组件内部不起作用

我有一个简单的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)

仍然没有任何反应。我在这里做错了什么?

javascript typescript reactjs

1
推荐指数
1
解决办法
2456
查看次数

标签 统计

javascript ×1

reactjs ×1

typescript ×1