【问题标题】:How to show or hide status bar on different screens in React Native如何在 React Native 的不同屏幕上显示或隐藏状态栏
【发布时间】:2021-06-09 08:33:48
【问题描述】:

我是本机反应的新手,并试图创建一些我想在不同屏幕上显示或隐藏状态栏的应用程序。在主屏幕中,我不想显示状态栏,因为我已经设置了它的属性 @987654321 @ 但是这样做它在其他屏幕上也不可见,我怎样才能让它在其他屏幕上可见。

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

下面是我的代码:

App.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;

有人告诉我如何才能达到预期的效果。

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    如果你不想在每个屏幕上都放 StatusBar...,你也可以使用 react-navigation 的useFocusEffect hook。 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);
      }
    });
    

    【讨论】:

    • 有什么办法可以改变不同屏幕状态栏的颜色。
    • 可以使用StatusBar的方法改变样式reactnative.dev/docs/statusbar#setbarstyle
    • 当我尝试您的解决方案时,我收到此错误`[TypeError: undefined is not a function (near '...(0, _react.useFocusEffect)...')]`。
    • @Digvijay useFocusEffect 应该从反应导航导入,而不是反应。 import { useFocusEffect } from '@react-navigation/native';
    • 是的,现在它工作正常我做错了导入。谢谢
    【解决方案2】:
    componentDidMount() {
       StatusBar.setHidden(false);
    }
    

    将此代码添加到每个页面的类中。写 truefalse 来显示和隐藏。

    【讨论】:

    • 我正在使用功能组件,所以我需要使用useEffect()钩子而不是componentDidMMount()吗?
    猜你喜欢
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    相关资源
    最近更新 更多