首页 > 解决方案 > 如何在 React Native 的不同屏幕上显示或隐藏状态栏

问题描述

我是新来的反应本机并试图创建一些我想在不同屏幕上显示或隐藏状态栏的应用程序。在主屏幕中我不想显示状态栏,因为我已经设置了它的属性hidden={true}但是这样做在其他屏幕上也看不到我如何使它在其他屏幕上可见。

OnboardHome屏幕中我想显示状态栏,在LoginRegister屏幕中我不想显示状态栏。

下面是我的代码:

应用程序.js

import React from 'react';
import {StatusBar} from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import Onboard from './components/Onboard';
import Login from './components/Login';
import Register from './components/Register';
import Home from './components/Home';

const Stack = createStackNavigator();

const App = () => {

return (
  <NavigationContainer>
   <StatusBar hidden={true}/>
    <Stack.Navigator>
     <Stack.Screen
       name="Onboard"
       component={Onboard}
       options={{ headerShown: false }} />
    <Stack.Screen
      name="Login"
      component={Login}
      options={{ headerShown: false }} />
    <Stack.Screen
      name="Register"
      component={Register} />
    <Stack.Screen
      name="Home"
      component={Home} 
      options={{ 
        headerLeft: null,
        headerTintColor:'white',
        headerStyle: {
          backgroundColor: '#e57373',
          elevation:0,
          shadowOpacity:0
       } }}/>  
    </Stack.Navigator>
  </NavigationContainer>
  );
};

export default App;

有人让我知道我怎样才能达到预期的结果。

标签: javascriptreactjsreact-native

解决方案


如果你不想在每个屏幕上都放 StatusBar...,你也可以使用useFocusEffectreact-navigation 的钩子。https://reactnavigation.org/docs/use-focus-effect/

它更干净且易于阅读。

import { useFocusEffect } from '@react-navigation/native';
useFocusEffect(() => {
  // This will run when component is `focused` or mounted.
  StatusBar.setHidden(true);

  // This will run when component is `blured` or unmounted.
  return () => {
    StatusBar.setHidden(false);
  }
});

推荐阅读