在 React v18 中,可以使用 useEffect 钩子来监听浏览器的倒退事件,并通过 window.onbeforeunload 方法弹出确认对话框。如果用户点击确认,则会离开页面,否则将取消离开。

下面是一个示例代码:

import React, { useEffect } from 'react';

const MyComponent = () => {
  useEffect(() => {
    const handleBeforeUnload = (event) => {
      event.preventDefault();
      event.returnValue = ''; // 在这里可以设置对话框的提示信息
    };

    window.onbeforeunload = handleBeforeUnload;

    return () => {
      window.onbeforeunload = null; // 清除监听器
    };
  }, []);

  return (
    // 组件的内容
  );
};

export default MyComponent;

请注意,在 React 组件中,推荐使用 useEffect 钩子来处理副作用,而在 useEffect 的清除函数中,我们将清除 window.onbeforeunload 方法的监听器,以避免内存泄漏。

另外,需要注意的是,浏览器对 onbeforeunload 方法的使用存在一些限制和差异,具体行为可能因浏览器而异

reactjs v18 当用户点击浏览器倒退时弹出确认对话框确定后再离开取消就不会离开

原文地址: https://www.cveoy.top/t/topic/inEV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录