react弹窗组件

reconnect-modal.tsx

TypeScript 复制代码
import { Modal } from 'antd';
import React, { useEffect, useState } from 'react';

interface ReconnectModalProps {
  open: boolean;
  onReconnect: () => void;
  onCancel: () => void;
}

const ReconnectModal: React.FC<ReconnectModalProps> = ({ open, onReconnect, onCancel }) => {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    setVisible(open);
  }, [open]);

  const handleOk = () => {
    onReconnect();
    setVisible(false);
  };

  const handleCancel = () => {
    onCancel();
    setVisible(false);
  };

  // 处理回车键
  useEffect(() => {
    const handleKeyPress = (e: KeyboardEvent) => {
      if (visible && e.key === 'Enter') {
        handleOk();
      }
    };

    window.addEventListener('keydown', handleKeyPress);
    return () => window.removeEventListener('keydown', handleKeyPress);
  }, [visible]);

  return (
    <Modal
      title="当前连接已断开,是否重新连接"
      open={visible}
      onOk={handleOk}
      onCancel={handleCancel}
      okText="重新连接"
      cancelText="取消"
    />
  );
};

export default ReconnectModal;

index.tsx

TypeScript 复制代码
import ReconnectModal from './reconnect-modal'; 
const [showReconnectModal, setShowReconnectModal] = useState(false);
  const reconnectDebounceRef = useRef<NodeJS.Timeout | null>(null);


// 防抖处理,确保只触发一次弹窗
  useEffect(() => {
    const subscription = socketService.sendEvent$.subscribe(event => {
      if (actionService?.reconnect && event === SendEventEnum.Reconnect) {
        // 防抖处理,确保只触发一次弹窗
        if (reconnectDebounceRef.current) {
          clearTimeout(reconnectDebounceRef.current);
        }
        reconnectDebounceRef.current = setTimeout(() => {
          setShowReconnectModal(true);
        }, 300);
      }
    });

    return () => {
      subscription.unsubscribe();
      if (reconnectDebounceRef.current) {
        clearTimeout(reconnectDebounceRef.current);
      }
    };
  }, [actionService, socketService.sendEvent$]);


<ReconnectModal
          open={showReconnectModal}
          onReconnect={() => {
            actionService?.reconnect?.();
            setShowReconnectModal(false);
          }}
          onCancel={() => {
            setShowReconnectModal(false);
          }}
        />
相关推荐
sunly_3 分钟前
TypeScript总结:16、面向对象速查
前端·javascript·typescript
张元清6 分钟前
React useInterval Hook:没有过期闭包的 setInterval (2026)
javascript·react.js
MXN_小南学前端7 分钟前
React超长文本域中实现“返回顶部”浮动按钮
前端·javascript·react.js
gs8014035 分钟前
解构 Cordis:面向“时空可组合性”的 TypeScript 元框架深度剖析
前端·javascript·typescript
Highcharts.js1 小时前
Highcharts大数据渲染模块Boost实战与参数最佳实践表
javascript·数据可视化·boost·highcharts·大数据渲染·加速配置·参数表
岁岁种桃花儿1 小时前
Vue核心语法第一篇:Vue是什么?
前端·javascript·vue.js
Highcharts.js2 小时前
数据可视化避坑指南 ——开发中常见图表错误与修复方案
javascript·信息可视化·数据可视化·highcharts·数据可视化避坑·修复方案
观无2 小时前
若依EasyExcel实现单元格合并
开发语言·前端·javascript
愚公搬代码2 小时前
【愚公系列】《Web应用安全》001-VMware的安装
前端·安全
xiaohaiAIgeo2 小时前
【2026年】HG/T 20656-2024化工暖通空调设计规范:新版标准的变化与影响
java·前端·javascript·科普知识