gpt4 book ai didi

react-native - 世博会中的方向变化监听器 react native 不触发?

转载 作者:行者123 更新时间:2023-12-05 02:06:50 24 4
gpt4 key购买 nike

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

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

最佳答案

这对我有用:

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

关于react-native - 世博会中的方向变化监听器 react native 不触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62315201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com