React-Native: Go back on android hardware back button pressed

前端 未结 6 2169
悲&欢浪女
悲&欢浪女 2021-02-05 06:14

I am trying to add going back on webview when the android backbutton was pressed and I still couldn\'t manage to make it work.

This is my code:



        
6条回答
  •  闹比i
    闹比i (楼主)
    2021-02-05 07:11

    If you are looking for a functional component solution.

    Note: canGoBack state is not required for performing back operation, it's just to save the current state, you can safely remove it if you want

    import React, { useState, useEffect, useRef } from "react"
    import { BackHandler, Platform } from "react-native"
    import { SafeAreaView } from "react-navigation"
    import { WebView } from "react-native-webview"
    
    const Webview = () => {
      const webView = useRef(null);
      const [canGoBack, setCanGoBack] = useState(false);
    
      useEffect(() => {
        if (Platform.OS === 'android') {
          BackHandler.addEventListener('hardwareBackPress', HandleBackPressed);
    
          return () => {
            BackHandler.removeEventListener('hardwareBackPress', HandleBackPressed);
          }
        }
      }, []); // INITIALIZE ONLY ONCE
    
      const HandleBackPressed = () => {
        if (webView.current) {
          webView.current.goBack();
          return true; // PREVENT DEFAULT BEHAVIOUR (EXITING THE APP)
        }
        return false;
      }
    
      return (
        
          "
            }}
            onNavigationStateChange={navState => setCanGoBack(navState.canGoBack)}
          />
        
      )
    }
    
    export default Webview;
    

提交回复
热议问题