React Native - Device back button handling

后端 未结 9 2119
感情败类
感情败类 2020-12-02 18:33

I want to check if there are more than one screens are on stack when device back button is hit. If yes, I want to show previous screen and if no, I want to exit app.

9条回答
  •  借酒劲吻你
    2020-12-02 19:05

    Here is how I implemented successfully using certain condition:

    componentWillMount() {
        BackHandler.addEventListener(
          'hardwareBackPress',
          this.handleBackButtonClick,
        );
      }
    
      componentWillUnmount() {
        BackHandler.removeEventListener(
          'hardwareBackPress',
          this.handleBackButtonClick,
        );
      }
    
      handleBackButtonClick = () => {
        //some condition
        if (this.state.isSearchBarActive) {
          this.setState({
            isSearchBarActive: false,
          });
          this.props.navigation.goBack(null);
          return true;
        }
        return false;
      };
    

提交回复
热议问题