首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用react在window.addEventListener中传递函数

如何使用react在window.addEventListener中传递函数
EN

Stack Overflow用户
提问于 2021-12-20 13:29:08
回答 1查看 374关注 0票数 2

我试图在关闭选项卡的时候添加一个函数,弹出并显示“休假”和“取消”,我想为特定按钮添加一个函数,例如,如果我单击“离开”按钮,它应该调用一个函数,如果我单击“取消”按钮,则应该调用其他函数。请提前帮我谢谢

代码语言:javascript
运行
复制
window.addEventListener("beforeunload", (ev) => {  
  ev.preventDefault();
    socket.current.emit(
      "logout_patient",
       history.location.state.data.doctorAlias,
       socket.current.id,
       history.location.state.data.patientId
    );  
  return ev.returnValue = 'Are you sure you want to close?'; 
});
EN

回答 1

Stack Overflow用户

发布于 2021-12-28 11:03:25

使用一个event('beforeunload').无法实现此功能

您可以使用窗口unload事件来检查用户对弹出窗口左边的单击。

window.requestAnimationFrame以检查您单击“取消”。

参考文献:https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event

代码语言:javascript
运行
复制
const onCancel = () => {
  console.log("I am the 2nd one.");
};
const onLeave = () => {
  console.log("I am the 3rd one.");

  // This loop is just to make sure that the event is fired
  for (var i = 0; i < 100000; i++) {
    console.log(event.returnValue);
  }
};

const onExit = (e) => {
  if (!e) e = window.event;
  e.returnValue = "You sure you want to leave?";
  if (e.stopPropagation) {
    e.stopPropagation();
    e.preventDefault();
  }
  console.log("I am the 1st one.");
  window.requestAnimationFrame(onCancel);
};

window.addEventListener("beforeunload", onExit, { capture: true });
window.addEventListener("unload", onLeave);

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70422559

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档