如何在React Native中为AppState使用Blur事件

时间:2019-09-09 18:38:01

标签: react-native

我需要一个示例,说明如何使用'blur'事件来响应本机AppState。我正在尝试响应应用程序未聚焦的情况,例如当用户拉通知抽屉,但我不断收到错误消息Invariant Violation: Trying to subscribe to unknown event: "blur"

3 个答案:

答案 0 :(得分:3)

基于与此功能登陆(https://github.com/facebook/react-native/commit/d45818fe47c53a670db933cf805910e227aa79c9)的提交相关联的标签,看来该功能仅从0.61开始可用,尚未登陆稳定版本。确保您运行的是0.61.0-rc.0或更高版本。

答案 1 :(得分:1)

根据正式的react native文档中提到的文档,AppState支持三种状态:

  

活动-该应用正在前台运行。

     

后台-应用在后台运行。用户是:   在另一个应用程序中   在主屏幕上   [Android]在另一个活动上(即使它是由您的应用启动的)

     

[iOS]无效-这是在前台和后台之间进行转换时以及在不活动期间(例如,进入多任务处理视图或来电时)发生的状态。

由于没有 blur 这样的状态,因此您遇到一个错误,指出它找不到此类事件。

修改

您必须在组件生命周期中将 blur 注册为事件,但是在此处必须谨慎并必须在注册 blur 事件之前确定平台。仅在android中可用,而在ios中不可用。

要注册活动,您必须执行以下操作:

import React from 'react';
import {AppState} from 'react-native';
class HandlingEvents extends React.Pure.Component {
    constructor(props) {
        super(props)
        // your state goes here...
    }
    componentDidMount() {
        // your event will be registered here, when your component is mounted on // the screen. 
        // Be cautious here, make a platform check here so as to avoid discrepancies in ios devices
        AppState.addEventListener('blur',this.handleBlurState)
    }
    componentWillUnMount() {
        // your event will be removed here, when your component gets unmounted from the screen.
        // Be cautious here, make a platform check here so as to avoid discrepancies in ios devices
        AppState.removeEventListener('blur',this.handleBlurState)
    }
    handleBlurState = (nextAppState) => {
        //this method will contain your entire logic, as to how you want to treat your component in this event.
        // As per the docs, since the state of your app will not changed, therefore you can continue your logic here by checking if the state of your app is **change** or not..
        if (AppState.currentState === "active" && nextAppState === "active") {
            //whatever task you want to perform here..;
        }
    }
}

答案 2 :(得分:1)

根据documentation。模糊是[仅限Android]

“ [[仅适用于Android],当用户未与应用进行主动交互时收到。在用户拉下通知抽屉的情况下很有用。AppState不会更改,但模糊事件将被触发。”

如果您仍想将其用于android,则只能在有条件的情况下将其用于android

import { Platform } from "react-native";

........

 componentDidMount() {
    if (Platform.OS === "android") {
      AppState.addEventListener("blur", this._handleAppStateBlur);
    }
  }

  componentWillUnmount() {
    if (Platform.OS === "android") {
      AppState.removeEventListener("blur", this._handleAppStateBlur);
    }
  }

  _handleAppStateBlur = () => {
    console.log("blur");
  };