在react函数组件中的使用:
// 浏览器的高度 默认设置为0;
const [height, setHeight] = useState(0);
const resizeUpdate = (e: any) => {
// 通过事件对象获取浏览器窗口的高度
const h = e.target.innerHeight - 266 - 16;
setHeight(h < 500 ? 500 : h);
};
useEffect(() => {
// 页面刚加载完成后获取浏览器窗口的大小
const h = window.innerHeight - 266 - 16;
setHeight(h < 500 ? 500 : h);
// 页面变化时获取浏览器窗口的大小
window.addEventListener('resize', resizeUpdate);
return () => {
// 组件销毁时移除监听事件
window.removeEventListener('resize', resizeUpdate);
};
}, []);