React Native 中的 Dimension.get('window').width 根据 SplashScreen 方向而不是当前方向?



我正在调整一个从iPhone到iPad的React Antive应用程序,我正面临一个奇怪的问题。我怀疑与RN的错误。当用户处于景观模式并启动应用程序时,它将在景观模式下具有飞溅屏幕,因此没有问题。但是该应用程序仍将Dimensions.get('window').width识别为景观模式宽度的宽度,即使我锁定屏幕以肖像。

我的应用结构是这样的。该应用程序的母体组件具有将应用程序锁定在肖像模式下的代码,例如:

var Orientation = require('react-native').NativeModules.Orientation;
componentWillMount(){
    Orientation.lockToPortrait();
}

从该初始组件中,其他组件通过路由器react-native-router-flux加载。这些组件UI组件内部使用React Nation 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,
  }
})

我根据Pedrosimao使用了此解决方法:

   Dimensions.addEventListener('change', e => {
  const{width,height}=(e.window)
  const getHeight = (percentage) => {
    if (width > height) {
      this.setState({orientation:'landscape'})
      return ((height * percentage) / 100)
    }else{
      this.setState({orientation:'portrait'})
    }

    return height
  }
  this.setState({width:width,height:height,height2:getHeight(50)})
});

当然,如果您至少不更改一次方向,这无效。您必须使用这样的初始状态:

         this.state={
           height2:   (Dimensions.get('window').height>Dimensions.get('window').width) ? Dimensions.get('window').height :(Dimensions.get('window').height*50)/100  ,

  }

最新更新