1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| import React, { forwardRef, useImperativeHandle, useState } from 'react';
interface ModalProps { children?: React.ReactNode; defaultVisible?: boolean; onAfterClose?: () => void }
const Modal: React.FC<ModalProps> = forwardRef((props, ref) => { const { children, defaultVisible, onAfterClose } = props; const [isVisible, setIsVisible] = useState(defaultVisible ?? true);
const openModal = () => { setIsVisible(true); };
const closeModal = () => { setIsVisible(false); onAfterClose?.() };
useImperativeHandle(ref, () => { return { openModal, closeModal, } });
return ( <div> {isVisible && ( <div style={{ position: 'fixed', top: 0, left: 0, width: '100%', height: '100%', backgroundColor: 'rgba(0, 0, 0, 0.5)', display: 'flex', justifyContent: 'center', alignItems: 'center', zIndex: 999, }} > <div style={{ backgroundColor: 'white', padding: '20px', borderRadius: '5px', boxShadow: '0 2px 4px rgba(0, 0, 0, 0.2)', }} > {children} <button onClick={closeModal} style={{ backgroundColor: '#4299e1', color: 'white', padding: '8px 16px', border: 'none', borderRadius: '4px', cursor: 'pointer', }} > Close </button> </div> </div> )} </div> ); });
export default Modal;
|