【问题标题】:What is the default unit for width, height, padding etc in React Native for iOS?React Native for iOS 中宽度、高度、填充等的默认单位是什么?
【发布时间】:2017-03-07 14:28:41
【问题描述】:

我正在为 iOS 构建一个 React Native 应用程序。 facebook 文档说宽度、高度、填充、边距等需要一个数字。

我想知道样式的默认单位是什么。

<View style={styles.box}>
   <Text style={styles.text}> Test Component </Text>
</View>

var styles = ReactNative.StyleSheet.create({
       box: {
          padding: 10,
          width:100,
          height:100,
       },
       text: {
          color: 'black',
          fontSize: 30,
       },
});

【问题讨论】:

  • 在 ReactNative 中默认单位是点或百分比,因为屏幕大小可能会根据不同的设备而有所不同,这样可以很容易地在不同的屏幕大小下渲染相同的组件。
  • 当您需要根据设备屏幕定义高度/宽度时,您可以导入Dimensions并在下面使用 var width = Dimensions.get('window').width; var height = Dimensions.get('window').height;直接在您的样式表中使用这些变量,您也可以添加或减去它们以生成不同的列和布局。

标签: react-native react-native-ios


【解决方案1】:

来自docs

React Native 中的所有维度都是无单位的,并且表示与密度无关的像素。以这种方式设置尺寸对于应该始终以完全相同的尺寸呈现的组件来说很常见,无论屏幕尺寸如何。

所以单位维度是dp。

【讨论】:

    【解决方案2】:

    我测试过。

    带有 DP 单元的 Android Native

    Android React Native

    带有点单元的 iOS 原生

    iOS React Native

    结果

    至少,RN中的单位与Android中的dp和iOS中的pt大致相同。

    另外,RN中的单位在Android中应用sp值来缩放字体大小。


    代码

    RN

          <SafeAreaView style={{flex: 1, backgroundColor: 'black'}}>
            <View
              style={{
                justifyContent: 'center',
                alignItems: 'center',
                backgroundColor: 'white',
                width: 150,
                height: 150,
                marginTop: 100,
                marginStart: 100,
              }}>
              <Text style={{color: 'black', textAlign: 'center', fontSize: 16}}>
                {'[React Native]\n100 x 100\nmargin top = 100\nmargin start = 100\n\nfontSize = 16\nㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁ'}
              </Text>
            </View>
          </SafeAreaView>
    

    安卓

            <TextView
                android:layout_width="150dp"
                android:layout_height="150dp"
                android:layout_marginStart="100dp"
                android:layout_marginTop="100dp"
                android:background="#fff"
                android:gravity="center"
                android:text="[ANDROID]\n\n100dp x 100dp\nmargin top = 100dp\nmargin start = 100dp\n\n textSize = 16sp\nㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁ"
                android:textColor="#000"
                android:textSize="16sp"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      • 2011-08-17
      • 2016-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多