【问题标题】:StatusBar backgroundColor removed after pressing back button (android)按下后退按钮后移除状态栏背景颜色(android)
【发布时间】:2018-05-06 08:06:12
【问题描述】:

我在 react native (Android) 中使用 StatusBar 组件。这是我的 App.js 组件中的示例代码:

import React, { Component } from 'react';
import { View, StatusBar } from 'react-native';
import { RootNavigator } from './components/Router';

export default class MainApp extends Component {

  render() {
    return (
      <View style={{flex: 1}}>
        <StatusBar backgroundColor='black' barStyle="light-content"/>
        <RootNavigator />
      </View>
    );
  }
}

当您启动应用程序、浏览整个应用程序以及置于后台然后返回时,状态栏正常工作。

按返回按钮退出应用程序时它不起作用。再次启动应用时,状态栏背景颜色突然变为灰色(默认颜色)。

这是一个已知的错误还是什么?我不知道如何解决这个问题。

【问题讨论】:

    标签: react-native


    【解决方案1】:

    好的,在提交问题后不久,我发现了另一种策略,使用命令式 API。我一开始就避免了,因为根据官方文档:

    对于使用组件并不理想的情况,有 也是一个命令式 API,在 零件。但是不建议使用静态 API 和 相同道具的组件,因为静态 API 设置的任何值 将在下一次渲染中被组件设置的覆盖。

    这是我修改后的代码:

    import React, { Component } from 'react';
    import { View, StatusBar } from 'react-native';
    import { RootNavigator } from './components/Router';
    
    export default class MainApp extends Component {
    
      componentWillMount() {
        StatusBar.setBackgroundColor('black');
      }
    
      render() {
        return (
          <View style={{flex: 1}}>
            <StatusBar backgroundColor='black' barStyle="light-content"/>
            <RootNavigator />
          </View>
        );
      }
    }
    

    现在看来这可以正常工作了。当我按下后退按钮并再次启动应用程序时,状态栏保持黑色。我不会宣布这是正确的答案,以防有人解释为什么会发生这种情况或更好的解决方案。

    编辑:这似乎也只有 90% 左右的时间有效。我注意到,有时,当按下返回按钮并返回状态栏时,状态栏仍然是灰色的。在这一点上绝对令人难以置信,我想 componentWillMount 并不总是被触发?

    Edit2:按照建议切换到 componentDidMount 而不是 componentWillMount 后,它现在似乎 100% 的时间都在工作。

    【讨论】:

    • 您可能想使用构造函数或componentDidMount,因为componentWillMount 被标记为不安全,很快就会被弃用reactjs.org/docs/react-component.html#unsafe_componentwillmount
    • 有趣,我会调整我的代码,看看是否更好。谢谢。
    • 嗯,使用 componentDidMount 似乎 100% 的时间都有效。有点令人惊讶,但很高兴知道。我想我不会再使用 componentWillMount 了。
    猜你喜欢
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 2017-03-27
    • 2022-11-21
    • 2021-12-16
    • 2012-08-23
    相关资源
    最近更新 更多