简体   繁体   中英

Back button is not disabling for particular screen in android React native

I am trying to disable android back button on home screen only. My code:

React.useEffect(() => {
        BackHandler.addEventListener('hardwareBackPress', handleBackBtnPressed);
        return () => {
          BackHandler.removeEventListener('hardwareBackPress', handleBackBtnPressed);
      }
    }, [])

    const handleBackBtnPressed = () => {
       navigation.goBack(null);
       return true
    }

const navigateToNextScreen = () => {
                navigation.push('Prmotions');
         }

If I remove navigation.goBack(null ); back button is disabled for all screen and with above code back button is not disabled at all. navigation.navigate("ScreenName") isn't working for mu scenario to move to next screen that's why I have used navigation.push

I handled it by putting this on all screens where I wanted to go back on back button press.

React.useEffect(() => {
        BackHandler.addEventListener('hardwareBackPress', handleBackBtnPressed);
        return () => {
          BackHandler.removeEventListener('hardwareBackPress', handleBackBtnPressed);
      }
    }, [])

    const handleBackBtnPressed = () => {
       
       navigation.goBack(null);
       return true
           
    }

and put this where I wanted not to go back.

  React.useEffect(() => {
        BackHandler.addEventListener('hardwareBackPress', handleBackBtnPressed);
        return () => {
          BackHandler.removeEventListener('hardwareBackPress', handleBackBtnPressed);
      }
    }, [])

    const handleBackBtnPressed = () => {

       return true
           
    }

I know this might not be best solution but it worked for me pretty well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM