后退按钮处理程序未调用本机反应

问题描述 投票:0回答:1

我正面临Android后退按钮处理程序的怪异问题。考虑我有3个屏幕,A,B和C。我正在使用堆栈导航器。 A导航到B,然后导航到C。

我希望能够从C返回到B,但不能从B返回到A。为此,在B中,我这样做:

async componentDidMount() {
    if (Platform.OS === "android") {
      BackHandler.addEventListener(
        "hardwareBackPress",
        this.onBackButtonPressAndroid.bind(this)
      );
    }
 }
 
 onBackButtonPressAndroid = () => {
    Alert.alert("Backed"); //this is just to test
    return true; //make it true to prevent going back
  };

在C中:

 if (Platform.OS === "android") {
      BackHandler.addEventListener(
        "hardwareBackPress",
        this.onBackButtonPressAndroid.bind(this)
      );
    }

onBackButtonPressAndroid = () => {
    this.props.navigation.goBack(null);
    return true;
  };

我已删除componentWillUnmount中的事件监听器。

[当我从A转到B并按向后按钮时,它的行为正确:它没有返回到A,并且我看到了警报。

但是当我从B转到C时,然后又回到B(使用后退按钮),如果我再次按下后退按钮,它将返回到A,但看不到警报。

为什么会这样?

更新如果我没有在C中设置事件处理程序,那么当我按下“后退”按钮时,我会看到警报!这意味着将调用B中的处理程序!

react-native react-native-android react-navigation
1个回答
0
投票

基于navigation lifecycle,而不是组件生命周期添加/删除事件侦听器。 C中不需要事件监听器。

import React from 'react'
import { Alert, Platform } from 'react-native'
import { NavigationEvents } from 'react-navigation'

export default class YourComponent extends React.Component {
  onBackPressAndroid = () => {
    Alert.alert('Cannot go back')
    return true
  }

  didFocus = () => BackHandler.addEventListener(
    'hardwareBackPress',
    this._onBackPressAndroid
  )

  willBlur = () => BackHandler.removeEventListener(
    'hardwareBackPress',
    this._onBackPressAndroid
  )

  render() {
    <>
      { Platform.OS === 'android'
        <NavigationEvents
          onDidFocus={this.didFocus}
          onWillBlur={this.willBlur}
        />
      }
      { /* your component render */ }
    </>
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.