简体   繁体   English

使用 react-navigation 更改状态栏颜色

[英]Change status bar color with react-navigation

I use a DrawerNavigator from react-navigation in my app.我在我的应用程序中使用了来自 react-navigation 的DrawerNavigator Without any customization, the Android status bar is blue, and not black.没有任何自定义,Android 状态栏是蓝色的,而不是黑色。

I tried to do我试着做

StatusBar.setBackgroundColor('#000000');

but it only works for a few seconds, and then it goes back to blue.但它只工作了几秒钟,然后又变回蓝色。 It seems that something I am using set the status bar color to blue.似乎我正在使用的东西将状态栏颜色设置为蓝色。 However, I tried to remove all dependencies and only keep react-navigation, and it still happens and the docs of react-navigation do not say anything about that.但是,我尝试删除所有依赖项并仅保留 react-navigation,但它仍然发生,并且 react-navigation 的文档对此没有任何说明。

How can I set the status bar color to black with react-navigation ?如何使用 react-navigation 将状态栏颜色设置为黑色?

I don't think there is any conflict between react-navigation and the StatusBar , but I think you should use the <StatusBar> component rather than the imperative API.我认为react-navigationStatusBar之间没有任何冲突,但我认为您应该使用<StatusBar>组件而不是命令式 API。 There's a high chance this is due to a re-render of your app and it just switch back to the default, with a component declare, you ensure it won't happen.这很可能是由于重新渲染您的应用程序,它只是切换回默认值,并声明了一个组件,您可以确保它不会发生。

<StatusBar backgroundColor='blue' barStyle='light-content' />

You can even have multiple ones per route, to change it depending on the path.您甚至可以为每条路线设置多个路线,以根据路径进行更改。 If you want to change it depending on the user and using redux , declare it in a connected component and pass the backgroundColor .如果您想根据用户和使用redux更改它,请在连接的组件中声明它并传递backgroundColor

Like Aperçu said no conflict between react-navigation and the StatusBar.就像 Aperçu 所说的,react-navigation 和 StatusBar 之间没有冲突。 Each screen should be able to set properties on the device's status bar, and the container defined in createNavigationContainer should get the options on state change, and apply them natively.每个屏幕都应该能够在设备的状态栏上设置属性,并且 createNavigationContainer 中定义的容器应该获得状态更改的选项,并在本机应用它们。 try this for StatusBar for entire App.为整个应用程序的 StatusBar 试试这个。

const AppContent = StackNavigator({
  Home: { screen: HomeScreen },
  Secondary: { screen: SecondaryScreen },
});

const App = () =>
  <View style={{flex: 1}}>
    <StatusBar backgroundColor="blue" barStyle="light-content"/> 
    // style the bar. barStyle is text and icon color od status bar.
   <AppContent />
 </View>;
import React, {Component} from 'react';
import {Text, TouchableOpacity, View, StatusBar} from 'react-native';
import {StackNavigator} from 'react-navigation';
import Icon from 'react-native-vector-icons/MaterialIcons';
import styles from "../styles/Style";

class ProfileScreen extends Component {

    static navigationOptions = ({navigation}) => {
        return {
            headerLeft: (
                <TouchableOpacity onPress={() => {
                    navigation.navigate('DrawerOpen');
                }}>
                    <Icon name="menu" size={30} color="#fff" style={styles.burgerIcon}/>
                </TouchableOpacity>
            ),
            title: 'My Profile',
            headerRight: (
                <Icon name={'edit'} size={30} color={'#fff'} style={styles.headerRightIcon}/>
            ),
            headerTintColor: "#fff",
            headerStyle: {
                backgroundColor: '#8BC83D',
                height: 56,
                elevation: null
            }
        };
    };

    render() {
        return (
            <View style={styles.screenContainer}>

                <StatusBar
                    backgroundColor="#7CB236"
                    barStyle="light-content"
                />
                <Text style={styles.welcome}>
                    I amsecond reder
                </Text>
            </View>
        );
    }
}
const ProfileScreenList = StackNavigator(
    {
    ProfileScreenIndex: {screen: ProfileScreen},
}
);
export default ProfileScreenList

Did you try setting your DrawerNavigator config ?您是否尝试设置 DrawerNavigator 配置? Doc says that contentOptions allows you to customize the drawer content. Doc 说contentOptions允许您自定义抽屉内容。

In the file where you define your DrawerNavigator , maybe your router.js file.在您定义DrawerNavigator的文件中,可能是您的router.js文件。 You should create your Navigator as:您应该将导航器创建为:

const MyApp = DrawerNavigator({
    Home: {
        screen: MyHomeScreen,
        contentOptions: {
            inactiveBackgroundColor: '#000000',
        }
   },
});

Maybe this page will help you: DrawerNavigator也许这个页面会帮助你: DrawerNavigator

Currently, your Drawer is certainly re-rendered at some point, that's why the color returns to blue.目前,您的抽屉肯定会在某个时候重新渲染,这就是颜色恢复为蓝色的原因。

On top of @Balthazar's answer, if you are using SafereaView then you might need to set the Status Bar color in your stylesheet like this:在@Balthazar 的回答之上,如果您使用的是 SafereaView,那么您可能需要像这样在样式表中设置状态栏颜色:

SafeArea: {
    flex: 1,
    backgroundColor: StatusBar.setBackgroundColor('black'),
    paddingTop: Platform.OS === "android" ? StatusBar.currentHeight : 0
 }

PS this code also detects the SafeAreaView in android devices with notch. PS 此代码还检测带有缺口的 android 设备中的 SafeAreaView。

To avoid manually handling mounting and unmounting of screens by eg updating a redux state, you can also use react navigation's useIsFocused.为了避免通过例如更新 redux 状态手动处理屏幕的安装和卸载,您还可以使用反应导航的 useIsFocused。

Let's say you want a single screen in a route to have a dark themed StatusBar:假设您希望路线中的单个屏幕具有深色主题的 StatusBar:

import { StatusBar, View } from 'react-native';
import { useIsFocused } from '@react-navigation/native';

export default function MyDarkScreen() {
    const isFocused = useIsFocused();
    return (
        <View>
            {
                isFocused &&
                <StatusBar
                    barStyle={'dark-content'}
                    translucent
                    backgroundColor="transparent"
                />
            }
            <SomeOtherComponent />
        </View>
    )
}

In your root component, you have to import在您的根组件中,您必须导入

StatusBar状态栏

You can follow the below code.您可以按照以下代码进行操作。

import React from 'react';
import {Text, View, StatusBar} from 'react-native';


const Home = () => {
      return (
        <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
           <StatusBar backgroundColor="#44A72C" barStyle="light-content" />
           <Text style={{fontFamily: 'UniNeueRegular-Italic'}}>Home Screen</Text>
        </View>
        );
      };
export default Home;

Thanks!谢谢!

You may want to use this, plugin navigationbar-react-native !你可能想使用这个插件navigationbar-react-native

1, Install plugin 1、安装插件

npm i navigationbar-react-native --save

2, Using 2、使用

 import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text,Image, View, TouchableOpacity, } from 'react-native'; import NavigationBar from 'navigationbar-react-native'; const ComponentLeft = () => { return( <View style={{ flex: 1, alignItems: 'flex-start'}} > <TouchableOpacity style={ {justifyContent:'center', flexDirection: 'row'}}> <Image source={require('./img/ic_back.png')} style={{ resizeMode: 'contain', width: 20, height: 20, alignSelf: 'center' }} /> <Text style={{ color: 'white', }}>Back Home</Text> </TouchableOpacity> </View> ); }; const ComponentCenter = () => { return( <View style={{ flex: 1, }}> <Image source={require('./img/ic_logo.png')} style={{resizeMode: 'contain', width: 200, height: 35, alignSelf: 'center' }} /> </View> ); }; const ComponentRight = () => { return( <View style={{ flex: 1, alignItems: 'flex-end', }}> <TouchableOpacity> <Text style={{ color: 'white', }}> Right </Text> </TouchableOpacity> </View> ); }; class App extends Component { render() { return ( <View style={styles.container}> <NavigationBar componentLeft = { () => {<ComponentLeft /> } componentCenter = { () => {<ComponentCenter /> } componentRight = { () => {<ComponentRight /> } navigationBarStyle= {{ backgroundColor: ''#215e79'' }} statusBarStyle = {{ barStyle: 'light-content', backgroundColor: '#215e79' }} /> </View> ); } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM