Modal Content
This is a simple modal component.
我在反应打字稿中创建了一个自定义模态组件。
// src/components/ui/Modal.tsx import React, { useState, useEffect, useRef } from 'react'; interface ModalProps { isOpen: boolean; onClose: () => void; children: React.ReactNode; dismissable?: boolean; closeOnEsc?: boolean; closeButtonLabel?: string; size?: 'small' | 'medium' | 'large'; position?: 'center' | 'top' | 'bottom'; } const Modal: React.FC= ({ isOpen, onClose, children, dismissable = true, closeOnEsc = true, closeButtonLabel = '×', size = 'medium', position = 'center', }) => { const [isModalOpen, setIsModalOpen] = useState(isOpen); const modalRef = useRef (null); useEffect(() => { setIsModalOpen(isOpen); }, [isOpen]); useEffect(() => { const handleOutsideClick = (event: MouseEvent) => { if (dismissable && modalRef.current && !modalRef.current.contains(event.target as Node)) { onClose(); } }; const handleEscKey = (event: KeyboardEvent) => { if (closeOnEsc && event.key === 'Escape') { onClose(); } }; if (isModalOpen) { document.addEventListener('mousedown', handleOutsideClick); document.addEventListener('keydown', handleEscKey); } return () => { document.removeEventListener('mousedown', handleOutsideClick); document.removeEventListener('keydown', handleEscKey); }; }, [isModalOpen, onClose, dismissable, closeOnEsc]); if (!isModalOpen) { return null; } const getSizeStyle = () => { switch (size) { case 'small': return { width: '300px', maxWidth: '100%' }; case 'large': return { width: '800px', maxWidth: '100%' }; default: return { width: '500px', maxWidth: '100%' }; } }; const getPositionStyle = () => { switch (position) { case 'top': return { alignItems: 'flex-start' }; case 'bottom': return { alignItems: 'flex-end' }; default: return { alignItems: 'center' }; } }; return ( ); }; export default Modal;{children}
import Modal from "@/components/ui/Modal"; import { useState } from "react"; export default function Home() { const [visible, setVisible] = useState(false); return (); } setVisible(false)}> Modal Content
This is a simple modal component.
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3