import { useState, useEffect } from 'react'; // 定义设备类型枚举 export enum DeviceType { MOBILE = 'mobile', TABLET = 'tablet', DESKTOP = 'desktop' } // 定义屏幕断点 const BREAKPOINTS = { MOBILE: 480, TABLET: 1024, DESKTOP: 1025 }; export function useDeviceType() { const [deviceType, setDeviceType] = useState(DeviceType.DESKTOP); const [windowSize, setWindowSize] = useState({ width: typeof window !== 'undefined' ? window.innerWidth : 0, height: typeof window !== 'undefined' ? window.innerHeight : 0 }); useEffect(() => { const getDeviceType = (width: number): DeviceType => { if (width <= BREAKPOINTS.MOBILE) return DeviceType.MOBILE; if (width <= BREAKPOINTS.TABLET) return DeviceType.TABLET; return DeviceType.DESKTOP; }; const handleResize = () => { const width = window.innerWidth; const height = window.innerHeight; setWindowSize({ width, height }); setDeviceType(getDeviceType(width)); // 移动端动态视口高度处理 if (width <= BREAKPOINTS.TABLET) { const vh = height * 0.01; document.documentElement.style.setProperty('--vh', `${vh}px`); } }; // 初始化 handleResize(); // 添加事件监听 window.addEventListener('resize', handleResize); window.addEventListener('orientationchange', () => { // 延迟处理以确保获取正确的视口尺寸 setTimeout(handleResize, 100); }); return () => { window.removeEventListener('resize', handleResize); window.removeEventListener('orientationchange', handleResize); }; }, []); return { deviceType, windowSize, isMobile: deviceType === DeviceType.MOBILE, isTablet: deviceType === DeviceType.TABLET, isDesktop: deviceType === DeviceType.DESKTOP, /** 是否为移动端设备(包括平板) */ isMobileDevice: deviceType === DeviceType.MOBILE || deviceType === DeviceType.TABLET }; }