通过 react-native-webview (React Native) 限制应用返回

Restrict app from going back via react-native-webview (React Native)

我已经使用 React 开发了一个网站,现在我一直在尝试通过 webview 在 React Native 中使用它。

问题:当我使用后退按钮时,应用程序退出。

原因:

我可以在此 else block in handleBackButton 中包含哪些内容以使应用程序不退出?

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

export default class Marketplace 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) {
      this.WEBVIEW_REF.current.goBack();
      return true;
    } else {
      console.log("Else block");
      // what to add here to restrict the app to exit
    }
  };

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

  render() {
    return (
      <SafeAreaView
        style={{
          flex: 1,
          paddingTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
        }}
      >
        <WebView
          source={{
            uri: "http://localhost:3000/",
          }}
          ref={this.WEBVIEW_REF}
          onNavigationStateChange={this.onNavigationStateChange}
        />
      </SafeAreaView>
    );
  }
}

如果你想限制用户退出应用程序,那么你也必须在 else 语句中 return true 或者你可以简单地这样做:-

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