我正在将 React Native 应用程序从 iPhone 适配到 iPad,但我遇到了一个奇怪的问题。我怀疑 RN 有 bug。
当用户处于横向模式并启动应用程序时,它将在横向模式下显示启动屏幕,这没有问题。但该应用程序不断识别Dimensions.get('window').width
即使在我将屏幕锁定为纵向后,其宽度仍为横向模式宽度。
我的应用程序结构是这样的。应用程序的母组件有一个将应用程序锁定为纵向模式的代码,如下所示:
var Orientation = require('react-native').NativeModules.Orientation;
componentWillMount(){
Orientation.lockToPortrait();
}
从该初始组件,其他组件通过路由器加载 react-native-router-flux
。在这些组件内部,UI 组件使用 React Native Dimensions API 进行样式设计。像这样:
<View style={{ width: Dimensions.get('window').width - 10}} />
它在 iPhone 上完美运行,因为 iPhone 在应用程序启动期间始终处于纵向模式。但在 iPad 上,当用户将屏幕设置为横向模式时(在应用程序启动期间),整个应用程序看起来很奇怪,因为 RN 正在将屏幕高度重新识别为屏幕宽度。当用户在纵向模式下启动应用程序时,不会发生同样的问题。自 Dimensions.get('window').width
以来,这种情况不应该发生在应用程序已锁定为纵向后立即调用。这对我来说毫无意义......
不幸的是,我确实也需要能够拥有横向模式,因为在某些屏幕内,我通过执行 Orientation.lockToLandscape()
强制用户处于横向模式。
这个问题有解决办法吗?
最佳答案
为了让我的应用程序快速运行,我想出了一个技巧,但我认为这不是最好的方法。我基本上通过测量屏幕来了解我的应用程序被锁定的方向。像这样:
const getWidth = (percentage: number) => {
if (Dimensions.get('window').width > Dimensions.get('window').height) {
return (Dimensions.get('window').height * percentage) / 100;
}
return (Dimensions.get('window').width * percentage) / 100;
};
const getHeight = (percentage: number) => {
if (Dimensions.get('window').width > Dimensions.get('window').height) {
return (Dimensions.get('window').width * percentage) / 100;
}
return (Dimensions.get('window').height * percentage) / 100;
};
之后,我可以创建适应屏幕方向的 Stylesheet.create() 对象。像这样:
StyleSheet.create({
fullWidth: {
width: getWidth(100) - 60,
}
})
而不是:
StyleSheet.create({
fullWidth: {
width: Dimensions.get('window').width - 60,
}
})
关于ios - React Native 中的 Dimension.get ('window' ).width 根据 SplashScreen 方向而不是当前方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55143165/