自定义 hooks组件

监听 windows size

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import React, { useCallback, useEffect, useState }  from "react";


function useWinSize() {

  const [size,setSize] = useState({
    width: document.documentElement.clientWidth,
    height: document.documentElement.clientHeight,
  })
  const onResize = useCallback(()=>{
    setSize({
      width: document.documentElement.clientWidth,
      height: document.documentElement.clientHeight,
    })

  },[])

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

  return size
}

export default useWinSize