React Hook监听窗口变化
程序员文章站
2022-06-21 12:27:14
...
React Hook监听窗口变化
引入
import React, { useState, useEffect } from "react";
const getWindowSize = () => ({
innerHeight: window.innerHeight,
innerWidth: window.innerWidth,
});
const [windowSize, setWindowSize] = useState(getWindowSize());
const handleResize = () => {
setWindowSize(getWindowSize());
};
useEffect(() => {
// 监听
window.addEventListener("resize", handleResize);
// 销毁
return () => window.removeEventListener("resize", handleResize);
});
使用
<div> {windowSize.innerHeight} </div>