64 lines
1.6 KiB
TypeScript
64 lines
1.6 KiB
TypeScript
|
|
/**
|
|||
|
|
* useScreenSize Hook
|
|||
|
|
* 屏幕尺寸检测 - 提供屏幕尺寸和断点信息
|
|||
|
|
*/
|
|||
|
|
|
|||
|
|
import { useState, useEffect, useMemo } from 'react';
|
|||
|
|
import { Dimensions, ScaledSize } from 'react-native';
|
|||
|
|
import { getBreakpoint, getFineBreakpoint } from './useBreakpoint';
|
|||
|
|
import type { BreakpointKey, FineBreakpointKey, ScreenSize } from './types';
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取窗口尺寸,支持屏幕旋转响应
|
|||
|
|
* 替代 Dimensions.get('window'),提供实时尺寸更新
|
|||
|
|
*/
|
|||
|
|
export function useWindowDimensions(): ScaledSize {
|
|||
|
|
const [dimensions, setDimensions] = useState(() => Dimensions.get('window'));
|
|||
|
|
|
|||
|
|
useEffect(() => {
|
|||
|
|
const subscription = Dimensions.addEventListener('change', ({ window }) => {
|
|||
|
|
setDimensions(window);
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
return () => {
|
|||
|
|
subscription.remove();
|
|||
|
|
};
|
|||
|
|
}, []);
|
|||
|
|
|
|||
|
|
return dimensions;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 屏幕尺寸 Hook
|
|||
|
|
* 提供屏幕尺寸信息和断点状态
|
|||
|
|
*
|
|||
|
|
* @returns 屏幕尺寸信息
|
|||
|
|
*
|
|||
|
|
* @example
|
|||
|
|
* const { width, height, isMobile, isTablet, isDesktop, isWide } = useScreenSize();
|
|||
|
|
*/
|
|||
|
|
export function useScreenSize(): ScreenSize & {
|
|||
|
|
breakpoint: BreakpointKey;
|
|||
|
|
fineBreakpoint: FineBreakpointKey;
|
|||
|
|
} {
|
|||
|
|
const { width, height } = useWindowDimensions();
|
|||
|
|
|
|||
|
|
return useMemo(() => {
|
|||
|
|
const breakpoint = getBreakpoint(width);
|
|||
|
|
const fineBreakpoint = getFineBreakpoint(width);
|
|||
|
|
|
|||
|
|
return {
|
|||
|
|
width,
|
|||
|
|
height,
|
|||
|
|
breakpoint,
|
|||
|
|
fineBreakpoint,
|
|||
|
|
isMobile: breakpoint === 'mobile',
|
|||
|
|
isTablet: breakpoint === 'tablet',
|
|||
|
|
isDesktop: breakpoint === 'desktop',
|
|||
|
|
isWide: breakpoint === 'wide',
|
|||
|
|
};
|
|||
|
|
}, [width, height]);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export default useScreenSize;
|