React Native, Detect screen rotation change using portrait mode

僤鯓⒐⒋嵵緔 提交于 2020-11-29 10:50:43

问题


I am using portrait mode in react-native application. But I want to capture the rotation event of the screen. Is there a way to do this?

Thanks...


回答1:


Well, you have several options. You can use the Dimensions API https://reactnative.dev/docs/dimensions

You can add a listener for Dimensions.change and you could do something like

function isPortrait() {
  const dim = Dimension.get("screen")
  return dim.height >= dim.width
}

function isLandscape() {
  const dim = Dimension.get("screen")
  return dim.width >= dim.height
}

now add listen to dimension chagnes with

Dimensions.addEventListener("change", () => {
// orientation has changed, check if it is portrait or landscape here
})

Another posibility is to use the one of the orientation packages available such as https://github.com/wonday/react-native-orientation-locker




回答2:


this function might help you
create a useOrientation.js file

import {useEffect, useState} from 'react';
import {Dimensions} from 'react-native';

export function useOrientation(){
  const [orientation, setOrientation] = useState("PORTRAIT");

  useEffect(() => {
    Dimensions.addEventListener('change', ({window:{width,height}})=>{
      if (width<height) {
        setOrientation("PORTRAIT")
      } else {
        setOrientation("LANDSCAPE")
    
      }
    })

  }, []);

  return orientation;
}


来源:https://stackoverflow.com/questions/62472029/react-native-detect-screen-rotation-change-using-portrait-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!