【两端同码】判断移动端还是PC端超级好用的方法

该博客介绍了一个React组件,它使用JavaScript的媒体查询判断设备是横屏还是竖屏,并根据屏幕尺寸和方向动态调整UI模式。当屏幕尺寸变化时,组件会监听并更新状态,以适配PC或移动设备。示例中展示了如何装饰组件以自动获取和应用当前的UI模式。
摘要由CSDN通过智能技术生成
// 源码实例
import React from 'react' 
// JavaScript 的媒体查询 
const mqlMedia = window.matchMedia('(orientation: portrait)')

function onMatchMediaChange(mql = window.matchMedia('(orientation: portrait)')) { 
  if (mql.matches) { 
    //竖屏 
    return 'portrait' 
  } else { 
    //横屏 
    return 'horizontal' 
  } 
} 
// 输出当前屏幕模式 
const getUiMode = (uiMode = '', mql) => { 
  if (uiMode) return uiMode 
  if (!('onorientationchange' in window)) return 'pc' 
  let status = onMatchMediaChange(mql) 
  let width = status === 'portrait' ? Math.min(window.innerWidth, window.innerHeight) : Math.max(window.innerWidth, window.innerHeight) 
  if (width > 1040) return 'pc' 
  return 'mobile' 
} 
const getIsPcMode = (uiMode) => uiMode === 'pc' 
/** 
 * UI 模式,判断逻辑 
 * @export 
 * @param {*} Cmp 
 * @returns 
 */ 
export function withUiMode(Cmp, options = {}) { 
  return class WithUIRem extends React.Component { 
    constructor(props) { 
      super(props) 
      let uiMode = getUiMode() 
      let isPCMode = getIsPcMode(uiMode) 
      this.state = { 
        uiMode: uiMode, 
        isPCMode: isPCMode, 
      } 
    } 
    // 横竖屏切换监听 
    componentDidMount() { 
      mqlMedia.addListener(this.changeUiMode) 
    } 
    componentWillUnmount() { 
      mqlMedia.removeListener(this.changeUiMode) 
    } 
    changeUiMode = (mql) => { 
      let newUiMode = getUiMode('', mql) 
      if (newUiMode !== this.state.uiMode) { 
        this.setState({ 
          isPCMode: getIsPcMode(newUiMode), 
          uiMode: newUiMode 
        }) 
      } 
    } 
    render() { 
      return <Cmp {...this.state} {...this.props} /> 
    } 
  } 
} 
export default (options) => { 
  return (Cmp) =>  withUiMode(Cmp, options) 
}

// 调用方法

// 装饰器的方式来使用 
@withUiMode() 
export default class Video extends React.Component { 
  render() { 
    const { isPCMode, uiMode } = this.props 
    return ( 
      <Page isPCMode={isPCMode}></Page> 
    ) 
  } 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值