【问题标题】:Negative marginTop not working as intended on Android, works fine in iOS负边距顶部无法在 Android 上按预期工作,但在 iOS 上工作正常
【发布时间】:2019-01-10 20:28:33
【问题描述】:

iOS 和 Android 模拟器示例。

代码:

<View style={styles.test}>
  <Text style={styles.header}>Header Example</Text>
  <Text>Lorem ipsum dolor sit amet</Text>
</View>

样式:

test: {
  borderWidth: 3,
  borderColor: "#000"
},
header: {
  marginTop: -10,
  backgroundColor: "yellow"
}

有人对为什么会发生这种情况有所了解吗?谢谢!

【问题讨论】:

    标签: android react-native layout margin


    【解决方案1】:

    负边距在 Android 上不起作用,因为在 &lt;View&gt; 上默认溢出设置为 hidden

    解决方法是使用 react-native-view-overflow 库而不是 &lt;View&gt;。这将允许您像预期的那样使用负边距。

    https://github.com/entria/react-native-view-overflow

    yarn add react-native-view-overflow
    

    添加到您的package.json 文件后,您需要稍微调整您的项目以使其正常工作。

    android/gradle/wrapper/gradle-wrapper.properties:

    -distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
    +distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
    

    android/build.gradle:

    buildscript {
         repositories {
             jcenter()
    +        google()
         }
         dependencies {
    -        classpath 'com.android.tools.build:gradle:2.2.3'
    +        classpath 'com.android.tools.build:gradle:3.1.0'
    
         // NOTE: Do not place your application dependencies here; they belong
         // in the individual module build.gradle files
    

    为了消除警告,在android/app/build.gradle:

         compileSdkVersion 23
    -    buildToolsVersion "23.0.1"
    +    buildToolsVersion "27.0.3"
         defaultConfig {
    

    运行yarn run android,您应该一切顺利。

    【讨论】: