react hooks实现离开页面和刷新页面提示
时间: 2023-11-30 21:11:35 浏览: 354
React Hooks提供了useEffect
Hook来实现在组件挂载和卸载时添加和移除事件监听器。可以使用useEffect
Hook来实现在离开页面或刷新页面时弹出确认提示框。具体实现方式如下:
- 在组件中使用
useEffect
Hook,在useEffect
的回调函数中添加beforeunload
事件监听器。使用return
语句来移除事件监听器。
import { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
const handleBeforeUnload = (event) => {
event.preventDefault();
event.returnValue = '';
}
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
}
}, []);
// ...
}
- 在事件监听器的回调函数中,阻止默认行为,设置
event.returnValue
为一个空字符串,这样在离开页面或刷新页面时会弹出一个确认提示框,提示用户是否离开当前页面。
const handleBeforeUnload = (event) => {
event.preventDefault();
event.returnValue = '';
}
- 如果需要自定义提示框的内容,可以在
event.returnValue
中设置需要提示的内容。
const handleBeforeUnload = (event) => {
event.preventDefault();
event.returnValue = '您确定要离开当前页面吗?';
}
通过上述方式,可以使用React Hooks实现在离开页面或刷新页面时弹出确认提示框的效果,并且可以自定义提示框的内容。
相关推荐

















