react-native - 世博会中的方向变化监听器反应原生不触发?
问题描述
我想在 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);
}
}, []);
推荐阅读
- javascript - node.js和python中相同问题解决方案的不同结果
- javascript - 在套件脚本 2.0 中加载保存的搜索时 search.run().getRange 出错
- html - Chrome浏览器计算错误的元素宽度
- c# - GMap.NET 我怎样才能做出准确的路由?
- powershell - PowerShell获取包含IP地址的行并将所有这些行保存在另一个文件中
- c# - .Net core 3.x Keyless Entity Types 避免创建表
- shopify - 将元字段暴露给 Storefront API 错误
- javascript - 在反应应用程序中更改密码减速器(axios + redux + jwt + bcrypt)
- ios - uitabbar隐藏Applozic SDK时出现黑条
- java - 我在 ICU4J 库中得到错误的输出