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);
          }}
        />
相关推荐
Old Uncle Tom30 分钟前
银行用户画像 -- 金融目标与需求意图
前端·人工智能·金融
IT_陈寒36 分钟前
Vue的响应式让我加班到凌晨3点,原来问题出在这
前端·人工智能·后端
东方小月36 分钟前
从0开发一个 Coding Agent(一):前言
前端·人工智能·typescript
恋猫de小郭37 分钟前
Flutter 全新真 3D 实现,用 flutter_scene 能开发一个「我的世界」
android·前端·flutter
ji_shuke1 小时前
远程排查 Web 系统问题:如何导出 HAR 文件协助定位
前端·问题排查
程序员爱钓鱼1 小时前
Rust String 与 &str 详解:字符串所有权、借用与转换
前端·后端·rust
码农学院2 小时前
GEO与SEO协同:从传统搜索到生成式搜索的平滑迁移路径
服务器·前端·python
To_OC9 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
咩咩啃树皮10 小时前
第40篇:Vue3组件化开发精讲——组件拆分、复用、父子通信、工程化架构
java·前端·架构