博览会中的方向改变侦听器反应本机不触发?

gpb*_*lio 4 react-native expo

我想检测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);
    });
  }, []);
Run Code Online (Sandbox Code Playgroud)

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

cab*_*ara 7

这对我有用:

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);
  };
}, []);

Run Code Online (Sandbox Code Playgroud)

  • 这对我不起作用,令人沮丧。 (4认同)