Dimensions.get('screen') 在 React Native 中不工作

Dimensions.get('screen') not working in React Native

我正在使用 react-native 尺寸来获取屏幕尺寸并确定用户是处于纵向模式还是横向模式......但是 Dimensions.get('screen').height 总是返回为 2 边中较长的边,即使当处于横向模式时......即Dimensions.get('screen').height 返回时总是大于 Dimensions.get('screen').width,即使在横向模式下也是如此

constructor(props) {
    super(props);
    this.state = {
      orientation: (Dimensions.get('screen').height >= Dimensions.get('screen').width ? 'portrait' : 'landscape')
    };

    Dimensions.addEventListener('change', () => {
      let orientation = (Dimensions.get('screen').height >= Dimensions.get('screen').width ? 'portrait' : 'landscape');
      this.setState({
        orientation: orientation
      });
    });
  }

使用useWindowDimensions()。 只需在您的根组件中放置类似这样的内容:

const SCREEN_WIDTH = useWindowDimensions().width;
const SCREEN_HEIGHT = useWindowDimensions().height;
return (
    <View style={{ width: SCREEN_WIDTH, minHeight: SCREEN_HEIGHT}} >
        //the rest of your app
    </View>
);