首页 > 解决方案 > 在 iOS 和 Android 中使用相同的代码但垂直边距的结果不同的 React Native 应用程序

问题描述

我在 android (Galaxy S7) 和 iOS (iPhone S8+) 上测试了一个简单的 render(),得到了我不明白的结果。

(而且,是的,我知道我可以在两个平台上设置不同的边距,但我想了解为什么结果与我的预期如此不同......)

这是我的代码:

import React, { Component } from 'react';
import { View, TextInput } from 'react-native';

export class Login extends Component {

    render() {
      return (
          <View style={{ marginLeft: 100 }}>
                <View style={{ marginTop: 25 }}>
                    <TextInput
                        style={{ color: 'black', width: 260 }}
                        value='email'
                    />
                    <View style={{ marginTop: -10,
                        borderBottomWidth: 1,
                        width: 200,
                        borderBottomColor: 'black' }} />
                </View>

                <View style={{ marginTop: 5 }}>
                    <TextInput
                        style={{ color: 'black', width: 260 }}
                        value='password'
                    />
                    <View style={{ marginTop: -10,
                        borderBottomWidth: 1,
                        width: 200,
                        borderBottomColor: 'black' }} />
                </View>
          </View>
      );
    }
}

这就是这段代码在安卓 Galaxy S7 模拟器(左)和 iPhone 8+ 模拟器上的显示方式。

安卓与 iOS

标签: react-nativereact-native-androidreact-native-ios

解决方案


其他答案和评论很好,但他们没有回答我的问题...... :)
我问为什么两个平台之间存在如此大的差异,而不是如何使用特定于平台的值进行修改。

我在这里找到了答案: react-native TextInput 在 Android 上更改高度时显示错误

引用:Android adds some default padding on top and bottom, you can reset them by adding paddingVertical: 0 to your element' style.

指定 时paddingVertical: 0,我们得到预期的结果:

在此处输入图像描述

这是更新的代码:
import React, { Component } from 'react';
import { View, TextInput } from 'react-native';

export class Login extends Component {

    render() {
      return (
          <View style={{ marginLeft: 100 }}>
                <View style={{ marginTop: 25 }}>
                    <TextInput
                        style={{ color: 'black', width: 260, paddingVertical: 0 }}
                        value='email'
                    />
                    <View style={{ marginTop: 0,
                        borderBottomWidth: 1,
                        width: 200,
                        borderBottomColor: 'black' }} />
                </View>

                <View style={{ marginTop: 15 }}>
                    <TextInput
                        style={{ color: 'black', width: 260, paddingVertical: 0 }}
                        value='password'
                    />
                    <View style={{ marginTop: 0,
                        borderBottomWidth: 1,
                        width: 200,
                        borderBottomColor: 'black' }} />
                </View>
          </View>
      );
    }
}

推荐阅读