React Native WebView App not exit on pressing back button

泄露秘密 提交于 2021-01-26 14:53:04

问题


React Native WebView App not exit on pressing back button after setting Go back functionality on back button pressed. I want go back functionality on pressing back button when webview is not on home page and when webview is on home page then exit the app.

export default class WebView 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 (
          <WebView
            source={{ uri: 'https://stackoverflow.com' }}
            ref={this.WEBVIEW_REF}
            onNavigationStateChange={this.onNavigationStateChange.bind(this)}

          />
        );
      }
    }

回答1:


Since you are managing the state of canGoBack inside onNavigationStateChange function, Change your handleBackButton function as below,

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

Check below complete example

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

export default class App extends Component {
  WEBVIEW_REF = React.createRef();

  state = {
    canGoBack: false,
  };

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

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

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

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

  render() {
    return (
      <WebView
        source={{ uri: "https://stackoverflow.com" }}
        ref={this.WEBVIEW_REF}
        onNavigationStateChange={this.onNavigationStateChange}
      />
    );
  }
}

Hope this helps you. Feel free for doubts.



来源:https://stackoverflow.com/questions/61102977/react-native-webview-app-not-exit-on-pressing-back-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!