简体   繁体   中英

React Native goBack() not being called correctly

My react-native-webview won't go back in any way. Back button press is correctly handled in android and logged in the right way, the WEBVIEW_REF is not null, but even if the "canGoBack" state is true, the webview just won't go back even if able. I am testing this code in Android

import React, { Component } from "react";
import { BackHandler } from "react-native";
import { WebView } from "react-native-webview";

export default class CustomWebView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      canGoBack: false,
    }
  }

  WEBVIEW_REF = React.createRef();

  componentDidMount() {
    BackHandler.addEventListener("hardwareBackPress", this.handleBackButton);
  }

  componentWillUnmount() {
    BackHandler.removeEventListener("hardwareBackPress", this.handleBackButton);
  }

  handleBackButton = () => {
    if (this.state.canGoBack) {
      console.log(this.WEBVIEW_REF.current);
      this.WEBVIEW_REF.current.goBack();  
    }
    return true;
  }

  onNavigationStateChange = (navState) => {
    console.log("navState", navState.canGoBack);
    this.setState({
      canGoBack: navState.canGoBack,
    });
  };

  render() {
    return (
    
        <WebView
        style={{width:400,height:200}}
          source={{
            uri: "https://www.google.com/",
          }}
          ref={this.WEBVIEW_REF}
          onNavigationStateChange={this.onNavigationStateChange}
        />
     
    );
  }
}

Try like this,

componentDidMount() {
if (Platform.OS === 'android') {
    this.backHandler = BackHandler.addEventListener('hardwareBackPress', function () {
        return true;
    });
}

}

componentWillUnmount() {
this.backHandler.remove();

}

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