// 源码实例
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>
)
}
}
【两端同码】判断移动端还是PC端超级好用的方法
最新推荐文章于 2024-11-12 08:45:00 发布