Files
smart-crop-ui/crop-x/src/hooks/useViewHeight.ts

57 lines
1.5 KiB
TypeScript

import { useEffect, useState } from 'react';
import { useLayoutStore } from '@/stores/useLayoutStore';
export const useViewHeight = () => {
const { setViewHeight, calculateMainBodyHeight } = useLayoutStore();
const [isClient, setIsClient] = useState(false);
// 确保在客户端执行
useEffect(() => {
setIsClient(true);
}, []);
const getViewHeight = () => {
if (!isClient) return 0;
// 获取视口高度
const height = window.innerHeight || document.documentElement.clientHeight;
return height;
};
useEffect(() => {
if (!isClient) return;
// 立即计算一次
const initialHeight = getViewHeight();
setViewHeight(initialHeight);
// 监听窗口大小变化
const handleResize = () => {
const newHeight = getViewHeight();
setViewHeight(newHeight);
};
// 监听方向变化
const handleOrientationChange = () => {
// 方向变化时稍微延迟计算,确保浏览器已经完成调整
setTimeout(() => {
const newHeight = getViewHeight();
setViewHeight(newHeight);
}, 100);
};
window.addEventListener('resize', handleResize, { passive: true });
window.addEventListener('orientationchange', handleOrientationChange, { passive: true });
// 清理函数
return () => {
window.removeEventListener('resize', handleResize);
window.removeEventListener('orientationchange', handleOrientationChange);
};
}, [isClient, setViewHeight]);
return {
getViewHeight,
isClient,
};
};