需求场景:
项目中有些样式,需要监听窗口大小更改
,做一些自适应处理
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)}