React监听窗口宽度变化 触发resize(Hooks版本)

需求场景:

项目中有些样式,需要监听窗口大小更改,做一些自适应处理

Code:

    const [screenW, setScreenW] = useState(document.documentElement.clientWidth || document.body.clientWidth)

	// 一些用到的需要自适应的变量
    const middleWidth = useMemo(() => {
        if (screenW < 1200) {
            return screenW - 64
        } else {
            return screenW - 256
        }
    }, [screenW])

    useEffect(() => {
        window.addEventListener("resize", handleWindowResize)
        return () => {
            window.removeEventListener("resize", handleWindowResize)
        }
    }, [])

    const handleWindowResize = () => {
        setScreenW(document.documentElement.clientWidth || document.body.clientWidth)
    }

你可能感兴趣的:(react.js,前端,javascript)