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

前端 未结 6 2173
悲&欢浪女
悲&欢浪女 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 06:49

    Wanted to add a full example in case it helps anyone:

    import React, { Component } from 'react';
    import {
      BackHandler,
      Platform,
      WebView,
    } from 'react-native';
    
    class ExampleWebView extends Component {
      webView = {
        canGoBack: false,
        ref: null,
      }
    
      onAndroidBackPress = () => {
        if (this.webView.canGoBack && this.webView.ref) {
          this.webView.ref.goBack();
          return true;
        }
        return false;
      }
    
      componentWillMount() {
        if (Platform.OS === 'android') {
          BackHandler.addEventListener('hardwareBackPress', this.onAndroidBackPress);
        }
      }
    
      componentWillUnmount() {
        if (Platform.OS === 'android') {
          BackHandler.removeEventListener('hardwareBackPress');
        }
      }
    
      render() {
        return (
           { this.webView.ref = webView; }}
            onNavigationStateChange={(navState) => { this.webView.canGoBack = navState.canGoBack; }}
          />
        );
      }
    }
    

提交回复
热议问题