33 lines
984 B
TypeScript
33 lines
984 B
TypeScript
import {useEffect, useState} from 'react'
|
|
import {TradePlatform} from '@/lib/models/trade'
|
|
|
|
// 设备检测Hook
|
|
export const usePlatformType = (): TradePlatform => {
|
|
// 在SSR环境下返回默认值
|
|
const [platform, setPlatform] = useState<TradePlatform>(() => {
|
|
if (typeof window === 'undefined') return TradePlatform.Desktop
|
|
return window.matchMedia('(max-width: 768px)').matches
|
|
? TradePlatform.Mobile
|
|
: TradePlatform.Desktop
|
|
})
|
|
|
|
useEffect(() => {
|
|
// 确保在客户端执行
|
|
if (typeof window === 'undefined') return
|
|
|
|
const checkPlatform = () => {
|
|
const isMobile = window.matchMedia('(max-width: 768px)').matches
|
|
setPlatform(isMobile ? TradePlatform.Mobile : TradePlatform.Desktop)
|
|
}
|
|
|
|
const mediaQuery = window.matchMedia('(max-width: 768px)')
|
|
mediaQuery.addEventListener('change', checkPlatform)
|
|
|
|
return () => {
|
|
mediaQuery.removeEventListener('change', checkPlatform)
|
|
}
|
|
}, [])
|
|
|
|
return platform
|
|
}
|