使用相同代码但在 iOS 和 Android 中产生不同结果的 React Native 应用程序

React Native app with same code but different result in iOS and Android

我是 React 的新手,我正在 Udemy 上一门关于 React Native 的课程。 我遇到了一个样式问题,它使用相同的代码和 StyleSheet 属性,文本中的 borderWith,它在 Android 和 iOS.

中看起来不同

当我向我的文本组件添加粗 "borderWith" 时,在 iOS 文本中它会自动从边框中获取一点边距,但 Android 将边框与文本。 我看到了一个使用平台模块或文件扩展名的解决方案,但我想知道我是否可以避免这种情况并使我的大部分代码与这两种设备相似。

const BoxScreen = () => {
    return (
        <View style={styles.viewStyle}>
            <Text style={styles.textStyle}>Box screen</Text>
        </View>
    );
};

const styles = StyleSheet.create({
    viewStyle: {
        borderWidth: 3,
        borderColor: 'black',
    },
    textStyle: {
        borderWidth: 10,
        borderColor: 'red',
        // marginVertical: 20,
        marginHorizontal: 20,
    }
}); 

结果iOS:

结果Android:

希望这有效!

const BoxScreen = () => {
    return (
        <View style={styles.viewStyle}>
            <View style={styles.textStyle}>
                <Text>Box screen</Text>
            </View>
        </View>
    );
};

const styles = StyleSheet.create({
    viewStyle: {
        borderWidth: 3,
        borderColor: 'black',
    },
    textStyle: {
        borderWidth: 10,
        borderColor: 'red',
        paddingHorizontal: 20,
    }
}); 

推荐使用响应式样式,查看这里: Link

不要在文本元素上使用边距,在视图元素上使用填充。

通常,兄弟姐妹之间 space 使用边距, space parents 和 children.

使用填充
   Try this,

   issue regarding android then you can use Platform.OS ,

   more information to visit,

https://facebook.github.io/react-native/docs/platform-specific-code

   const BoxScreen = () => {
        return (
            <View style={styles.viewStyle}>
                <Text style={styles.textStyle}>Box screen</Text>
            </View>
        );
    };

    const styles = StyleSheet.create({
        viewStyle: {
            borderWidth: 3,
            borderColor: 'black',
        },
        textStyle: {
            borderWidth: 10,
            borderColor: 'red',
            // marginVertical: 20,
            marginHorizontal: Platform.OS === 'ios' ? 20 : 30,
            padding:Platform.OS === 'ios' ? 0 : 5

        }
    }); 

尝试使用文本样式

 textAlign: 'center'

有趣的是我以前从未注意到它。
那是因为保证金!
ios 元素的总高度和宽度计算为边框、填充和元素内部高度的总和,因此如果给它一个边距,它会推动边框和填充它是就像边框在框的外面
Android 中,外部高度被渲染为内部高度。就像边框在盒子里 增长。
因此,要解决此问题,您应该调整框中央的文本以在两个平台上都获得所需的结果:

class App extends Component {
  render () {
    return(
        <View style={styles.box}>
          <Text style={styles.title}> Box Screen</Text>
        </View>
    );
  }
}

const styles={
  title : {
    flex : 1,
    justifyContent : 'center',
    borderWidth : 10,
    borderColor : 'red',
    margin: 20,
    padding: 20,
  },
  box : {
    borderWidth : 3,
    borderColor : 'black',
  },
}