react 自定义封装获取视口宽高hooks

hooks.js

  import React,{useEffect,useState} from 'react';
export const useWindowsize = ()=>{
  let [width,setwidth] = useState("0px")
  let [height,setHeight] = useState("0px")
  useEffect(()=>{
      setwidth(document.documentElement.clientWidth)
      setHeight(document.documentElement.clientHeight)
    },[])
    useEffect(()=>{
      const handleResize = ()=>{
        setwidth(document.documentElement.clientWidth)
        setHeight(document.documentElement.clientHeight)
      }
      window.addEventListener("resize",handleResize,false)
      return ()=>{
        window.removeEventListener("resize",handleResize,false)
      }
    },[])
    return [width,height]
}

组件

import {useWindowsize} from "../hooks"
 const [width,height] = useWindowsize()

你可能感兴趣的:(react 自定义封装获取视口宽高hooks)