在 React Native 中使用嵌套导航更改所有屏幕状态栏颜色的最佳方法是什么?

bra*_*hal 3 ios react-native react-navigation expo

我目前正在使用 Expo 和 React Navigation 在我的应用程序的深色主题和浅色主题之间切换。唯一的问题是 I\xe2\x80\x99m 无法根据主题更改 iOS 上的状态栏颜色。

\n

我在抽屉导航器中嵌套了一个选项卡导航器,但是当我切换嵌套导航中所有屏幕的主题时,我\xe2\x80\x99m 无法弄清楚如何更改 iOS 上的状态栏颜色。这就是我的抽屉导航器的一部分的样子。

\n
 <themeContext.Provider value={themeData}>\n    <NavigationContainer theme={theme == 'Light' ? CustomDefaultTheme : CustomDarkTheme}>\n      <Drawer.Navigator\n        screenOptions={{\n          headerShown: false,\n          swipeEdgeWidth: 0,\n          drawerActiveBackgroundColor: '#e8e4f0',\n          drawerActiveTintColor: '#8a76b6',\n          drawerInactiveBackgroundColor: 'transparent',\n          drawerInactiveTintColor: '#bcbcc1',\n\n        }}\n
Run Code Online (Sandbox Code Playgroud)\n

Vis*_*war 5

您可以使用react-native的StatusBar方法来更改它的背景或barStyle -

StatusBar.setBarStyle(theme == 'Light' ? 'dark-content' : 'light-content');
StatusBar.setBackgroundColor(theme == 'Light' ? '#fff' : '#000')
Run Code Online (Sandbox Code Playgroud)

当您更改主题时调用上面的函数。

如果您想更改所有屏幕的状态栏背景,您可以从根组件更改它的另一种方法,那么您可以这样做 -

import { SafeAreaView, StatusBar } from 'react-native'

...
<SafeAreaView style={{flex: 1}}>
  <StatusBar
      backgroundColor={theme == 'Light' ? '#fff' : '#000'}
      barStyle={theme == 'Light' ? 'dark-content' : 'light-content'}
  />
  <ThemeContext.Provider value={themeData}>
    <NavigationContainer theme={theme == 'Light' ? CustomDefaultTheme : CustomDarkTheme}>
       <Drawer.Navigator
         screenOptions={{
           ...
         }}>
        ...
      </Drawer.Navigator>
    </NavigationContainer>
  </ThemeContext.Provider>
</SafeAreaView>
Run Code Online (Sandbox Code Playgroud)