【问题标题】:Not getting accurate screen height and width with Dimensions in react native在 react native 中无法使用尺寸获得准确的屏幕高度和宽度
【发布时间】:2021-01-04 06:02:59
【问题描述】:

我正在尝试使用Dimensions 来获取设备屏幕的高度和宽度。

下面是我的代码:

return (
        <SafeAreaView style={styles.safeAreaView}>
            <View style={styles.mainContainer}>
                
            </View>
            <View style={styles.footerContainer}>
                <Text>Hello</Text>
            </View>
        </SafeAreaView>
    );

这是我正在使用的风格:

const styles = StyleSheet.create({
    
    mainContainer: {
        height: (Dimensions.get('window').height / 100) * 80,
        backgroundColor: "blue",
    },
    footerContainer: {
        top:  (Dimensions.get('window').height / 100) * 80,
        height: (Dimensions.get('window').height / 100) * 20,
        width: Dimensions.get('window').width / 100 * 100,
        backgroundColor: "yellow",
        position: "absolute",
        justifyContent: "flex-end"
    }
});

输出

如您所见,我看不到&lt;Text&gt;Hello&lt;/Text&gt;。 我正在用(Dimensions.get('window').height / 100) * 80 做基础数学。我将屏幕的总高度除以百,然后将结果乘以所需的数字:这将给我屏幕的百分比高度。我不想使用弹性。我想继续我正在遵循的过程。我只想知道为什么我的Hello 文字会出现在屏幕下方。

它适用于某些设备,但不适用于其他设备。它适用于 Pixel4 模拟器,但不适用于 Pixel3 模拟器。如果我的尺寸计算是正确的,那为什么它不能在所有设备上工作??

【问题讨论】:

  • 这可能是由于某些安卓设备的底部按钮。或者您可以删除 justifyContent: "flex-end" 以在所有设备上显示
  • @pankajchaturvedi 我有设计,我必须提供justiyContent: "flex-end"。我也在使用SafeAreaView,所以它应该可以工作吗?对吗??
  • 您正在使用 SafeAreaView,但您强制它具有 20% 的屏幕高度。它可以走出屏幕。 @pankajchaturvedi 是对的,在某些设备上,底部按钮也会添加到屏幕高度。我不明白你为什么不想使用 flex 但如果你坚持使用尺寸 api,你可以看看这个答案:stackoverflow.com/a/60561393/5793132
  • 您的 safeAreaView 样式如何?

标签: react-native


【解决方案1】:

“为什么它不能在所有设备上运行??” - 这是因为 Dimensions.get('...').height 目前在 Android 中存在错误 see this issue.

要获得 WINDOW_HEIGHT_NO_STATUS_BARSTATUS_BAR_HEIGHT(所以窗口全高 = WINDOW_HEIGHT_NO_STATUS_BAR + STATUS_BAR_HEIGHT)

我使用了这个代码:

import { getStatusBarHeight } from 'react-native-status-bar-height'
import { initialWindowMetrics } from 'react-native-safe-area-context'

export const STATUS_BAR_HEIGHT = getStatusBarHeight()

export const WINDOW_HEIGHT_NO_STATUS_BAR = Platform.OS !== 'ios' && Dimensions.get('screen').height !== Dimensions.get('window').height && STATUS_BAR_HEIGHT > 24 
? Dimensions.get('screen').height - STATUS_BAR_HEIGHT 
: STATUS_BAR_HEIGHT > 24 
  ? Dimensions.get('window').height - STATUS_BAR_HEIGHT 
  : Dimensions.get('window').height + initialWindowMetrics.insets.bottom === Dimensions.get('screen').height 
    ? Dimensions.get('window').height - STATUS_BAR_HEIGHT 
    : Dimensions.get('window').height

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多