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

前端 未结 6 2222
悲&欢浪女
悲&欢浪女 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:12

    This might help someone as the above solutions didn't solve my problem....

    import React, { Component } from 'react';
    import {
      BackHandler,
      WebView,
    } from 'react-native';
    
    export default class App extends Component {
    
    constructor(props) {
        super(props);
        this.WEBVIEW_REF = React.createRef();
    }
    
    componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
    }
    
    componentWillUnmount() {
      BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
    }
    
    handleBackButton = ()=>{
       this.WEBVIEW_REF.current.goBack();
       return true;
    }
    
    onNavigationStateChange(navState) {
      this.setState({
        canGoBack: navState.canGoBack
      });
    }
    
    render(){
       return (
        
        )
    
     }
    }
    

提交回复
热议问题