utils/getWidth.js
export const getWidth = () => {
return { width: window.innerWidth };
};
页面引用
const [windowWidth, setWindowWidth] = useState(getWidth());
// 标记一下
useEffect(() => {
const widthSize = () => {
setWindowWidth(getWidth());
};
window.addEventListener("resize", widthSize);
return () => {
window.removeEventListener("resize", widthSize);
};
}, []);