在 React 18 中,你可以使用 beforeunload 事件来实现在用户离开页面之前弹出确认对话框的功能。你可以在组件的生命周期方法 componentDidMount 中添加事件监听器,然后在 componentWillUnmount 中移除监听器。

下面是一个示例代码:

import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    const handleBeforeUnload = (event) => {
      event.preventDefault();
      event.returnValue = ''; // 必须添加一个空字符串,否则对话框可能不会弹出
    };

    window.addEventListener('beforeunload', handleBeforeUnload);

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, []);

  return (
    <div>
      <h1>My Component</h1>
      <p>This is my component content.</p>
    </div>
  );
}

export default MyComponent;

在上面的示例中,我们在 componentDidMount 中添加了 beforeunload 事件的监听器,并在 componentWillUnmount 中移除了监听器。当用户尝试离开页面时,浏览器会弹出确认对话框。如果用户点击确认,页面会被卸载,如果用户点击取消,页面将保持不变。

请注意,由于 beforeunload 事件的行为在不同的浏览器中可能会有所不同,因此无法定制对话框的外观和样式。但是,你可以改变对话框的文本内容,以提供自定义的消息给用户

reactjs v18 当用户倒退或者刷新等等即是说将要离开本页面时弹出确认对话框确定后再离开取消就不会离开

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

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