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);
          }}
        />
相关推荐
阿正的梦工坊20 小时前
JavaScript 微任务与宏任务完全指南
开发语言·javascript·ecmascript
懂懂tty20 小时前
CRA 迁移 Rspack(实战)
前端·架构
小码哥_常1 天前
Kotlin 助力 Android 启动“大提速”
前端
GreenTea1 天前
AI 时代,工程师的不可替代性在哪里
前端·人工智能·后端
Jagger_1 天前
能不能别再弄低代码害人了
前端
朦胧之1 天前
AI 编程开发思维
前端·后端·ai编程
踩着两条虫1 天前
VTJ:快速开始
前端·低代码·架构
木斯佳1 天前
前端八股文面经大全:携程前端一面(2026-04-17)·面经深度解析
前端·状态模式
2301_799073021 天前
基于 Next.js + 火山引擎 AI 的电商素材智能生成工具实战——字节跳动前端训练营成果
javascript·人工智能·火山引擎
Java后端的Ai之路1 天前
LangChain ReAct Agent 核心技术问答
前端·react.js·langchain