【问题标题】:BackHandler 'hardwareBackPress working only Single time | React nativeBackHandler 'hardwareBackPress 只工作一次 |反应原生
【发布时间】:2018-11-01 08:41:37
【问题描述】:

我需要处理 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;
            }

        }

我需要在菜单视图上处理这个问题,因为我需要在其他组件的后按时显示默认组件。

【问题讨论】:

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


    【解决方案1】:
     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{
                 //not this
                //this.state.mainView = "Main";
                // use this
               this.setState({mainView: "Main"})
                this.forceUpdate();
                return true;
            }
    
        }
    

    【讨论】:

    • 感谢您的快速响应,但第二次监听器无法正常工作,我的意思是像这种方法 handleBackPress 没有被调用:(
    • 当你点击返回按钮时会发生什么?你离开组件了吗?因为如果你离开组件 componentWillUnmount 运行并移除注册的监听器。
    【解决方案2】:
     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();
      }, []);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-25
      • 1970-01-01
      • 2019-03-21
      相关资源
      最近更新 更多