我正在尝试在React中使用beforeUnload事件,在选项卡关闭或用户刷新页面之前执行操作,但该事件从未触发...我正在将此效果用于App组件。
import "./styles/global.css";
import Home from "./sections/Home";
import Header from "./components/Header";
import Footer from "./components/Footer";
import { useEffect } from "react";
function App() {
useEffect(() => {
const onBeforeUnload = (ev) => {
ev.returnValue = "Anything you wanna put here!";
return "Anything here as well, doesn't matter!";
};
window.addEventListener("beforeunload", onBeforeUnload);
return () => {
window.removeEventListener("beforeunload", onBeforeUnload);
};
}, []);
return (
<div className="App">
<Header />
<Home />
<Footer />
</div>
);
}
export default App;