BackHandler'hardwareBackPress仅工作一次反应本机

时间:2018-11-01 08:41:38

标签: android react-native react-native-android react-native-navigation onbackpressed

我需要处理Android设备上的Back Press,但是我的BackHandler只能一次使用。

这是我的代码段-

 componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
    }
    componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
    }

        handleBackPress = () => {

            console.log("handleBackPress Called on RootMenuView : current View ? : " + this.state.mainView);

            if (this.state.mainView === "Main"){
                return false;
            } else{
                this.state.mainView = "Main";
                this.forceUpdate();
                return true;
            }

        }

我需要在菜单视图中处理此问题,因为我需要在按回其他组件时显示默认组件。

2 个答案:

答案 0 :(得分:2)

    <a href="#"><span>2015 Highlights</span></a>

答案 1 :(得分:0)

 useEffect(() => {
    const backAction = () => {
      if(props.navigation.isFocused()){
      Alert.alert("Hold on!", "Are you sure you want to go back?", [
        {
          text: "Cancel",
          onPress: () =>console.log("hi"),
          style: "cancel"
        },
        { text: "YES", onPress: () => BackHandler.exitApp() }
      ]);
      return false;
    };}

    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      backAction
    );

    return () => backHandler.remove();
  }, []);