React Native IOS 状态栏背景

React Native IOS Status Bar background

由于将 backgroundColor 道具应用到 StatusBar 组件未在 IOS 上应用。我需要设置 SafeAreaView 的背景颜色以获得我想要的效果,它工作正常但在 iPhone X 上它将在屏幕底部具有相同的颜色。我该如何解决这个问题?

React-Native 在iOS 平台上不支持 StatusBar 的背景颜色更改,但在 Android 平台上可以(https://facebook.github.io/react-native/docs/statusbar#backgroundcolor)。我为您的问题写了一个解决方法。您可以放心使用

import React, {Component} from "react";
import {StyleSheet, StatusBar, View, Platform} from "react-native";

const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight;

function StatusBarPlaceHolder() {
    return (
        <View style={{
            width: "100%",
            height: STATUS_BAR_HEIGHT,
            backgroundColor: "blue"
        }}>
            <StatusBar
                barStyle="light-content"
            />
        </View>
    );
}

class App extends Component {
    render() {
        return (
            <View style={{flex: 1}}>
                <StatusBarPlaceHolder/>
                ...YourContent
            </View>
        );
    }
}

export default App;

对于 SafeAreaView:

import React, {Component} from "react";
import {StyleSheet, StatusBar, View, Platform} from "react-native";
import SafeAreaView from "react-native-safe-area-view";
//You can also use react-navigation package for SafeAreaView with forceInset.

const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight;

function StatusBarPlaceHolder() {
    return (
        <View style={{
            width: "100%",
            height: STATUS_BAR_HEIGHT,
            backgroundColor: "blue"
        }}>
            <StatusBar
                barStyle="light-content"
            />
        </View>
    );
}

class App extends Component {
    render() {
        return (
            <SafeAreaView style={{flex:1}}
                forceInset={{top: 'never'}}>
                <StatusBarPlaceHolder/>
                ...YourContent
            </SafeAreaView>
        );
    }
}

export default App;

支持 iPhone X

除了 @sdkcy 的回答,对于 iPhone X STATUS_BAR_HEIGHT 不能20 岁。

我通过安装以下库解决了这个问题:

https://www.npmjs.com/package/react-native-status-bar-height

安装

npm install --save react-native-status-bar-height

导入

import { getStatusBarHeight } from 'react-native-status-bar-height';

并像这样更新 STATUS_BAR_HEIGHT:

const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? getStatusBarHeight() : 0;

最后,我还将 Android 的高度更改为 0,因为它会影响 NavigationBar 的高度,但如果它对您来说效果很好,您可以保持不变。

希望对您有所帮助。

iPhone X 使用 44pt 高状态栏

const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 44:StatusBar.currentHeight;

参考这些备忘单