React Native - 如何检测主页按钮是否被按下? [英] React Native - How to detect home button is pressed or not?

查看:44
本文介绍了React Native - 如何检测主页按钮是否被按下?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用以下代码知道场景何时出现在屏幕上:

I can know when the scene is on screen using following code:

this.subs = [
   this.props.navigation.addListener('didFocus', this.loadOfflineData)
];

但是,如果我想检测场景何时失焦.我想知道我该怎么办.

But , if I want to detect when scene is out of focus. I 'm wondering what should I do .

基本上我想检测用户是否按下主页按钮,然后我想执行一些操作.

Basically I want to detect if the user press home button and then I want to perform some action.

任何建议.

推荐答案

您可以使用 AppState 以了解应用程序何时进入后台.

You can use AppState to know when an app is put into the background.

AppState 可以告诉你应用是在前台还是后台,并在状态改变时通知你.

AppState can tell you if the app is in the foreground or background, and notify you when the state changes.

这是一个使用 AppState 的简单示例:

Here is a simple example of using AppState:

import React, {Component} from 'react';
import {AppState, Text} from 'react-native';

class AppStateExample extends Component {
  state = {
    appState: AppState.currentState,
  };

  componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
  }

  componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
  }

  _handleAppStateChange = (nextAppState) => {
    if ( this.state.appState.match(/inactive|background/) && nextAppState === 'active' ) {
      console.log('App has come to the foreground!');
    } else {
      console.log('App has gone to the background!');
      // start your background task here
    }
    this.setState({appState: nextAppState});
  };

  render() {
    return <Text>Current state is: {this.state.appState}</Text>;
  }
}

这篇关于React Native - 如何检测主页按钮是否被按下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆