ReactJS 中的屏幕方向 [英] Screen orientation in ReactJS

查看:27
本文介绍了ReactJS 中的屏幕方向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 ReactJS 中获取方向类型和锁定方向?Screen Orientation API 不适用于 ReactJS,或者我只是不知道如何安装和使用它.请指导我执行上述操作.谢谢.

how to get orientation type and lock orientation in ReactJS? The Screen Orientation API doesn't work with ReactJS or I just don't know how to install and use it. Please guide me to do the above. Thanks.

推荐答案

从您的帖子中可以看出您的用例不是很清楚.但是,纯 JavaScript (Window.matchMedia() 方法)以及一些 CSS(orientation) 和用于调整窗口大小的事件侦听器,可以让您获取窗口方向并将其存储在应用程序状态中.

Your use case is not that clear from your post. However, plain JavaScript (Window.matchMedia() method) along with a bit of CSS (media query for orientation) and event listener for window resize, may let you grab window orientation and store it within app state.

以下代码演示了这个概念(由于 stacksnippets 的限制,没有实时演示,所以你可以在 stackblitz):

Following code demonstrates that concept (no live-demo due to stacksnippets limitations, so you may try that out at stackblitz):

import React, { useState, useEffect } from 'react'
import { render } from 'react-dom'

const rootNode = document.getElementById('root')

const App = () => {
    const isLandscape = () => window.matchMedia('(orientation:landscape)').matches,
          [orientation, setOrientation] = useState(isLandscape() ? 'landscape' : 'portrait'),
          onWindowResize = () => {              
            clearTimeout(window.resizeLag)
            window.resizeLag = setTimeout(() => {
              delete window.resizeLag                       
              setOrientation(isLandscape() ? 'landscape' : 'portrait')
            }, 200)
          }

    useEffect(() => (
      onWindowResize(),
      window.addEventListener('resize', onWindowResize),
      () => window.removeEventListener('resize', onWindowResize)
    ),[])

    return (
      <div>{orientation}</div>
    )
}

render (
  <App />,
  rootNode
)

ps 虽然上面是非常可行的,但它可能会在短时间内变得更加全面,因为 window.screen.orientation(目前的工作草案)将使其符合标准,还有一项改进em> 可能看起来很明显(听听 orientationchange 事件,而不是 resize),但在我看来,对于桌面版应用程序来说,前者似乎没有那么顺利

p.s. while above is pretty viable, it may become even more comprehensive in a short while as window.screen.orientation (working draft currently) will make it to the standard, one more improvement may seem obvious (listen for orientationchange event, rather than resize), but former doesn't seem to me working so smoothly for desktop version of the app

这篇关于ReactJS 中的屏幕方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆