方向改变听众在博览会React本地不开火?

ocebsuys  于 2023-01-09  发布在  React
关注(0)|答案(4)|浏览(145)

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

当我旋转器械时,没有日志,因此无法击发,这是怎么回事?

4nkexdtk

4nkexdtk1#

这对我很有效:

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

yptwkmov2#

您应该在app.json / app.config.js中将orientation字段设置为default。如果此字段设置为其他值,则应用将锁定到指定的方向。
相关文档在这里:https://docs.expo.dev/versions/v46.0.0/config/app/#orientation

628mspwn

628mspwn3#

这是一条什么都不做的线路。坏了,被窃听了,POS?以上所有的?

ScreenOrientation.addOrientationChangeListener((e) => {
 console.log(e);
});
aelbi1ox

aelbi1ox4#

我也遇到了同样的问题。侦听器函数从未启动。
expo-sensors添加到我的项目中似乎为我修复了回调。我认为expo-screen-orientation可能依赖于expo-sensors
新增步骤:

  1. npx expo install expo-sensors
    1.重建你的expo开发客户端。(对我来说,这个命令是eas build --profile simulator,但是这取决于你的eas配置)
    之后,侦听器回调函数开始触发。
    下面是添加侦听器的代码片段:
useEffect(() => {
    ScreenOrientation.addOrientationChangeListener((e) => {
      console.log(e)
    })
  }, [])

相关问题