React Hook监听页面大小
程序员文章站
2022-03-04 17:56:18
...
import React, { useState, useEffect } from 'react'
// 函数要以use开头
function useWindowSize() {
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)
})
return windowSize
}
上一篇: 监听页面大小的改变
下一篇: 面试总结-Java基础