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);
          }}
        />
相关推荐
竹林8187 小时前
用 wagmi v2 和 viem 手写 NFT 市场批量上架功能,我踩遍了所有异步坑
javascript
ayqy贾杰7 小时前
基层管理的三板斧,在AI时代行不通了
前端·后端·团队管理
Apifox7 小时前
Apifox 5 月更新|Postman 导入优化、Runner 支持非 root 运行、请求代码自动带鉴权
前端·后端·安全
zithern_juejin7 小时前
数组扁平化
javascript
清溪5497 小时前
n8n表达式沙箱逃逸至RCE漏洞-CVE-2025-68613复现
javascript·安全
miaowmiaow7 小时前
PSD2Code 近期更新与深度解析:从设计稿到生产级代码的完整技术栈
前端·人工智能·ai编程
Hilaku8 小时前
多标签页并发请求导致 Token 刷新失败?只有 15行代码就能解决 !
前端·javascript·程序员
烛衔溟8 小时前
TypeScript 类的静态成员与静态方法
开发语言·javascript·typescript
Nile8 小时前
解密Palantir系列一:4. Ontology 不是哲学
开发语言·前端·javascript
Highcharts8 小时前
如何创建蛛网地图|气泡事件+全球发布+关联组合图表开发示例
javascript