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

前端 未结 6 2170
悲&欢浪女
悲&欢浪女 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条回答
  •  一整个雨季
    2021-02-05 07:09

    Here's a solution with Typescript and useRef and useEffect hooks.

    I didn't use canGoBack, but it seems to work regardless.

    import React, { useEffect, useRef } from 'react';
    import { BackHandler } from 'react-native';
    import WebView from 'react-native-webview';
    
    const WebViewWrapper = (): JSX.Element => {
      const webview = useRef(null);
      const onAndroidBackPress = (): boolean => {
        if (webview.current) {
          webview.current.goBack();
          return true; // prevent default behavior (exit app)
        }
        return false;
      };
      useEffect((): (() => void) => {
        BackHandler.addEventListener('hardwareBackPress', onAndroidBackPress);
        return (): void => {
          BackHandler.removeEventListener('hardwareBackPress', onAndroidBackPress);
        };
      }, []); // Never re-run this effect
      return (
        
      )
    }
    

提交回复
热议问题