import { useEffect, useRef, type ReactNode } from 'react'; import { createPortal } from 'react-dom'; import { useBackToClose } from '@/lib/useBackToClose'; import styles from './Drawer.module.css'; interface Props { label: string; onClose: () => void; children: ReactNode } /** 手机的左侧抽屉:遮罩是纯色,返回键关闭(与 Sheet 一致) */ export function Drawer({ label, onClose, children }: Props) { const ref = useRef(null); const close = useRef(onClose); useEffect(() => { close.current = onClose; }, [onClose]); useBackToClose(onClose); useEffect(() => { const prev = document.activeElement as HTMLElement | null; ref.current?.focus(); const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') close.current(); }; window.addEventListener('keydown', onKey); return () => { window.removeEventListener('keydown', onKey); prev?.focus(); }; }, []); return createPortal(
event.stopPropagation()}> {children}
, document.body, ); }