React Native - Device back button handling

后端 未结 9 2111
感情败类
感情败类 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 18:53

    In react hooks

    import { BackHandler } from 'react-native';
    
    function handleBackButtonClick() {
        navigation.goBack();
        return true;
      }
    
      useEffect(() => {
        BackHandler.addEventListener('hardwareBackPress', handleBackButtonClick);
        return () => {
          BackHandler.removeEventListener('hardwareBackPress', handleBackButtonClick);
        };
      }, []);
    

提交回复
热议问题