简体   繁体   English

React Native 如何获取设备的方向

[英]React Native How to get orientation of device

The current code below will get the orientation however if the device is in Landscape view and you open the app it shows portrait view.下面的当前代码将获取方向,但是如果设备处于横向视图并且您打开应用程序,它会显示纵向视图。 After manual rotating the device it code below works correctly How do I get the orientation of the device when app starts.手动旋转设备后,它下面的代码正常工作如何在应用程序启动时获取设备的方向。 #React #React Native #React #React Native

const ViewControllerProvider = (props) => {
  const [orientation, setOrientation] = useState('PORTRAIT');

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

  return (
    <ViewControllerContext.Provider value={{orientation}}>
      {props.children}
    </ViewControllerContext.Provider>
  );
};

export {ViewControllerProvider, ViewControllerContext};

When you add the listener, you can also do a manual call to get the initial orientation:添加侦听器时,您还可以手动调用以获取初始方向:

  const [orientation, setOrientation] = useState('LANDSCAPE');

  const determineAndSetOrientation = () => {
    let width = Dimensions.get('window').width;
    let height = Dimensions.get('window').height;

    if (width < height) {
        setOrientation('PORTRAIT');
      } else {
        setOrientation('LANDSCAPE');
      }
  }

  useEffect(() => {

    determineAndSetOrientation();
    Dimensions.addEventListener('change', determineAndSetOrientation);

    return () => {
      Dimensions.removeEventListener('change', determineAndSetOrientation)
    }
  }, []);

Also probably a good idea to remove the event listener (see the return statement).删除事件侦听器也可能是一个好主意(请参阅return语句)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM