React Native WebView App 不会在按下后退按钮时退出

React Native WebView App not exit on pressing back button

在按下后退按钮时设置返回功能后,React Native WebView 应用程序不会在按下后退按钮时退出。我想在 webview 不在主页上时按返回按钮返回功能,当 webview 在主页上时退出应用程序。

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://whosebug.com' }}
            ref={this.WEBVIEW_REF}
            onNavigationStateChange={this.onNavigationStateChange.bind(this)}

          />
        );
      }
    }

由于您在 onNavigationStateChange 函数中管理 canGoBack 的状态,请按如下方式更改 handleBackButton 函数,

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

查看下面的完整示例

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://whosebug.com" }}
        ref={this.WEBVIEW_REF}
        onNavigationStateChange={this.onNavigationStateChange}
      />
    );
  }
}

希望对您有所帮助。有疑问欢迎留言。