简体   繁体   中英

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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