# react 自定义 hook - 移动端检测
# 场景:
服务于移动端和 pc 端使用不同布局的情况
# 实现
通过设备标识来判断是否是移动端设备
const isSmallDeviceByUA = () => { | |
const userAgent = navigator.userAgent.toLowerCase(); | |
const mobileKeywords = ['android', 'iphone', 'windows phone']; | |
for (const keyword of mobileKeywords) { | |
if (userAgent.indexOf(keyword) !== -1) { | |
return true; | |
} | |
} | |
return false; | |
} | |
export const useSmallDevice = () => { | |
const [isSmallDevice,toggleDevice]=useState<boolean>(isSmallDeviceByUA()); | |
const resizeEvent= debounce(()=>{ | |
toggleDevice(isSmallDeviceByUA()); | |
},300); | |
useEffect(()=>{ | |
window.addEventListener('resize',resizeEvent); | |
return ()=>{ | |
window.removeEventListener('resize',resizeEvent) | |
} | |
},[]) | |
return isSmallDevice; | |
} |