📅  最后修改于: 2022-03-11 15:03:07.141000             🧑  作者: Mango
import { useState, useEffect } from 'react';
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height
};
}
export default function useWindowDimensions() {
const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowDimensions;
}
// Adapted answer from https://stackoverflow.com/questions/36862334/get-viewport-window-height-in-reactjs
// Best suited for using in SPA.