/** * 媒体查询模拟 Hook */ import { useMemo } from 'react'; import { useScreenSize } from './useScreenSize'; import { useOrientation } from './useOrientation'; interface MediaQueryOptions { minWidth?: number; maxWidth?: number; minHeight?: number; maxHeight?: number; orientation?: 'portrait' | 'landscape'; } /** * 模拟 CSS 媒体查询 * * @param query - 查询条件 * @returns 是否匹配 * * @example * const isMinWidth768 = useMediaQuery({ minWidth: 768 }); * const isPortrait = useMediaQuery({ orientation: 'portrait' }); */ export function useMediaQuery(query: MediaQueryOptions): boolean { const { width, height } = useScreenSize(); const { orientation: currentOrientation } = useOrientation(); return useMemo(() => { if (query.minWidth !== undefined && width < query.minWidth) return false; if (query.maxWidth !== undefined && width > query.maxWidth) return false; if (query.minHeight !== undefined && height < query.minHeight) return false; if (query.maxHeight !== undefined && height > query.maxHeight) return false; if (query.orientation !== undefined && currentOrientation !== query.orientation) return false; return true; }, [width, height, currentOrientation, query]); }