如何防止布局与iOS状态栏重叠

我正在研究React Native导航教程 。 我发现所有的布局开始从屏幕的顶部加载,而不是在状态栏的下面。 这导致大多数布局与状态栏重叠。 我可以通过在加载视图时添加填充来解决这个问题。 这是实际的方式吗? 我不认为手动添加填充是解决这个问题的一种实际方法。 有没有更好的方法来解决这个问题?

import React, { Component } from 'react'; import { View, Text, Navigator } from 'react-native'; export default class MyScene extends Component { static get defaultProps() { return { title : 'MyScene' }; } render() { return ( <View style={{padding: 20}}> //padding to prevent overlap <Text>Hi! My name is {this.props.title}.</Text> </View> ) } } 

下面显示添加填充之前和之后的屏幕截图。 在添加填充之前

添加填充后

有一个非常简单的方法来解决这个问题。 制作一个组件。

您可以创build一个StatusBar组件,并在父组件中的第一个视图包装器之后首先调用它。

这是我使用的代码:

 'use strict' import React, {Component} from 'react'; import {View, Text, StyleSheet, Platform} from 'react-native'; class StatusBarBackground extends Component{ render(){ return( <View style={[styles.statusBarBackground, this.props.style || {}]}> //This part is just so you can change the color of the status bar from the parents by passing it as a prop </View> ); } } const styles = StyleSheet.create({ statusBarBackground: { height: (Platform.OS === 'ios') ? 20 : 0, //this is just to test if the platform is iOS to give it a height of 20, else, no height (Android apps have their own status bar) backgroundColor: "white", } }) module.exports= StatusBarBackground 

做完这些并导出到你的主要组件后,就像这样调用它:

 import StatusBarBackground from './YourPath/StatusBarBackground' export default class MyScene extends Component { render(){ return( <View> <StatusBarBackground style={{backgroundColor:'MidnightBlue '}}/> </View> ) } } 

你可以通过向你的导航条组件添加一个填充来处理这个问题,或者只是在视图树顶部的状态栏上添加一个与facebook应用程序的背景颜色相同的视图。