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

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

    class MyComponent extends Component {
        state = {};
        componentDidMount(){
             BackHandler.addEventListener('hardwareBackPress', this.backHandler);
        }
        componentWillUnmount(){
             BackHandler.removeEventListener('hardwareBackPress', this.backHandler);
        }
        backHandler = () => {
            if(this.state.backButtonEnabled) {
                this.refs[WEBVIEW_REF].goBack();
                return true;
            }
        }
    }
    

    1) Bind your handler 2) Do not forget to removeListener on unmount.

提交回复
热议问题