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);
          }}
        />
相关推荐
蜗牛攻城狮2 小时前
微前端四大方案选型对比与最佳实践:qiankun、micro-app、wujie、Module Federation
前端·微前端·qiankun·前端架构·micro-app·wujie
她说可以呀3 小时前
Vue插槽
前端·javascript·vue.js
qq_448011164 小时前
Vue + Jinja2两套模版与法冲突造成undefinedError
前端·javascript·vue.js
aixingpan4 小时前
aixingpan.cn API开发文档:前端查询夏令时和时区接口指南
前端·php
2601_958352904 小时前
23.5×19mm 换掉一整条音频链?|A-68 集成了什么:ADC / DAC / 24.576MHz 时钟 / AEC / 波束降噪,主控仅需 6 根线
前端·音视频·ai降噪·回声消除·语音模块
志尊宝5 小时前
AI原生前端开发(039):AI辅助的Nuxt 4全栈开发
前端·vue.js·ai-native
FRing036 小时前
JavaScript入门到精通三十二(深拷贝、浅拷贝、递归函数)
开发语言·前端·javascript
excel6 小时前
双 Token 与前端使用 Crypto 公私钥鉴权换 Token,哪种方案更好?
前端·后端
外收内放6 小时前
Python基础语法练习题(73)
java·前端·python
鸿蒙开发7 小时前
Three.js 首帧卡顿排查:compileAsync 之后,为什么还会停一下?
react.js·three.js