useBreakPointHook

useBreakpoint Hook —在React中获取媒体查询断点

怎么测量窗口宽度?

要获取断点,我们需要测量浏览器的宽度,然后在window对象上获取该宽度。window对象具有两个宽度:outerWidthinnerWidth,这里我们使用innerWidth

window.innerWidth每当我们调整窗口大小时,我们都会进行测量。

window.addEventListener('resize',dosomethingWithWidth)

因此,每当我们调整窗口大小时,resize都会触发该事件并计算innerWidth,但是实现这样的事情存在一个小问题,每当我们重新调整窗口大小时,都会触发回调函数, 回影响运行性能。因此这里我们可以使用节流函数来减少触发频率。关于节流函数详情请看节流函数与防抖函数.

计算Breakpoint

基于常见设备类型的Breakpoint

  • 如果宽度小于320像素,则该设备会特别小,以表示xs
  • 如果宽度等于或大于320像素且小于720像素,则该设备很小,由表示sm
  • 如果宽度等于或大于720像素且小于1024像素,则该设备为中等,由表示md
  • 如果宽度等于或大于1024px,则该设备很大,由表示lg

useBreakpoint Hook

现在连接React中的所有零碎部分,以获得完整的useBreakpoint自定义Hook。

首先,我们将使用useState挂钩创建状态,该状态将存储我们当前的设备类型。

1
2
3
4
5
6
7
8
9
10
11
12
const  getDeviceBp  =  (width) =>  {
if(width < 320 ) {
return 'xs'
} else if (width > = 320 && width < 720 ) {
return “ sm”
} else if (width > = 720 && width < 1024 ) {
return 'md'
} else if (width > = 1024 ) {
return “ lg”
}
}
const [brkPnt,setBrkPnt] = useState(()=> getDeviceConfig(window.innerWidth))

其次,我们使用useEffect来监听变化

1
2
3
useEffect(()=> {
window.addEventListener('resize',throttle(setBrkPnt(getDeviceBp(window.innerWidth))))
})

最后,为了防止每次调用hook时就注册监听事件,并且在组件卸载时候注销我们我们需要从useEffect回调函数中返回一个函数,该回调函数将在我们的组件被卸载时执行,并将所有逻辑放入其中

1
2
3
4
5
useEffect(()=> {
const calInnerWidth = throttle(setBrkPnt(getDeviceBp(window.innerWidth)));
window.addEventListener('resize',calInnerWidth)
return ()=> window.removeEventListener('resize',calInnerWidth)
},[])

集合

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
import {useState, useEffect} from 'react';
import throttle from './throttle';

const getDeviceBp = (width) => {
if(width < 320 ) {
return 'xs'
} else if (width > = 320 && width < 720 ) {
return “ sm”
} else if (width > = 720 && width < 1024 ) {
return 'md'
} else if (width > = 1024 ) {
return “ lg”
}
}

const useBreakpoint = () => {
const [brkPnt,setBrkPnt] = useState(()=> getDeviceConfig(window.innerWidth))

useEffect(()=> {
const calInnerWidth = throttle(setBrkPnt(getDeviceBp(window.innerWidth)));
window.addEventListener('resize',calInnerWidth)
return ()=> window.removeEventListener('resize',calInnerWidth)
},[])

return brkPnt;
}
export default useBreakpoint;
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2020 Ruoyu Wang
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信