Desarrollé un sitio web usando reaccionar y ahora he estado tratando de usar esto a través de webview en reaccionar nativo.
Problema: cuando uso el botón Atrás, la aplicación se cierra.
Razón:
onNavigationStateChange
usa el historial, navState.canGoBack() devuelve falso. ¿Qué puedo incluir en este else block in handleBackButton
para que la aplicación no se cierre?
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> ); } }
si desea impedir que el usuario salga de la aplicación, también tendrá que devolver verdadero en la declaración else o simplemente puede hacer esto:
handleBackButton = () => { if (this.state.canGoBack) { this.WEBVIEW_REF.current.goBack(); } return true; }