首页 > 解决方案 > 世博会中的方向变化监听器反应原生不触发?

问题描述

我想在 expo react native 中检测设备的当前方向,这是我的代码不起作用:

import {
 Dimensions,
} from 'react-native';
import * as ScreenOrientation from 'expo-screen-orientation';**
const App = () => {
...
useEffect(() => {
    const isPortrait = () => {
      const dimension = Dimensions.get('screen');
      return dimension.height >= dimension.width;
    };
    Dimensions.addEventListener('change', () => {
      const orientation = isPortrait() ? 'portrait' : 'landscape';
      console.log('Dimensions orientation', orientation);
    });
    ScreenOrientation.addOrientationChangeListener((e) => {
      console.log('e ', e);
    });
  }, []);

怎么当我旋转设备时没有日志所以它没有触发?

标签: react-nativeexpo

解决方案


这对我有用:

const [orientation, setOrientation] = useState(ScreenOrientation.Orientation.PORTRAIT_UP);

useEffect(()=>{
    // set initial orientation
    ScreenOrientation.getOrientationAsync()
    .then((info) =>{
      setOrientation(info.orientation);
    });

    // subscribe to future changes
    const subscription = ScreenOrientation.addOrientationChangeListener((evt)=>{
      setOrientation(evt.orientationInfo.orientation);
    });

    // return a clean up function to unsubscribe from notifications
    return ()=>{
      ScreenOrientation.removeOrientationChangeListener(subscription);
    }
  }, []);

推荐阅读