React Native Webview 使 Android 上的后退按钮返回

Per*_*ril 1 webview reactjs react-native

当我单击 Android 上的硬件按钮时,应用程序关闭,我想返回上一页,

这是我的代码

import { StatusBar } from 'expo-status-bar';
import React, { useState } from 'react';
import { ActivityIndicator, Linking, SafeAreaView, StyleSheet, Text, View } from 'react-native';
import { WebView } from 'react-native-webview';

export default function App() {
  const [isLoadong, setLoading] = useState(false);

  return (
    <SafeAreaView style={styles.safeArea}>
      <WebView
          originWhiteList={['*']}
          source={{ uri: 'https://google.com' }}
          style={styles.container } 
          onLoadStart={(syntheticEvent) => {
          setLoading(true);
        }}
        onShouldStartLoadWithRequest={(event)=>{
          if (event.navigationType === 'click') {
            if (!event.url.match(/(google\.com\/*)/) ) {
              Linking.openURL(event.url)
              return false
              }
              return true
          }else{
            return true;
          }
        }}
        onLoadEnd={(syntheticEvent) => {
          setLoading(false);
        }} />
        {isLoadong && (
            <ActivityIndicator
              color="#234356"
              size="large"
              style={styles.loading}
            />
        )}
        </SafeAreaView>
    );
}



const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: '#234356'
  },
  loading: {
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    alignItems: 'center',
    justifyContent: 'center'
  },
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
Run Code Online (Sandbox Code Playgroud)

Jig*_*ani 6

在react-native-webview库中有内置的goBack()方法,您可以使用API​​方法来实现webview的后退导航。

为此,您必须获取react-native-webview组件的引用并从引用对象中调用方法。

此外,您还可以将侦听器放在 Android Native Back Button Press 事件上,以调用 webview 的 goBack() 方法。

尝试以下代码...

    import { StatusBar } from 'expo-status-bar';
    import React, { useState, useRef, useEffect } from 'react';
    import { ActivityIndicator, Linking, SafeAreaView, StyleSheet, BackHandler } from 'react-native';
    import { WebView } from 'react-native-webview';

    export default function App() {
        const webViewRef = useRef()
        const [isLoadong, setLoading] = useState(false);

        const handleBackButtonPress = () => {
            try {
                webViewRef.current?.goBack()
            } catch (err) {
                console.log("[handleBackButtonPress] Error : ", err.message)
            }
        }

        useEffect(() => {
            BackHandler.addEventListener("hardwareBackPress", handleBackButtonPress)
            return () => {
                BackHandler.removeEventListener("hardwareBackPress", handleBackButtonPress)
            };
        }, []);
  
        return (
          <SafeAreaView style={styles.safeArea}>
            <WebView
                originWhiteList={['*']}
                source={{ uri: 'https://google.com' }}
                style={styles.container} 
                ref={webViewRef}
                onLoadStart={(syntheticEvent) => {
                    setLoading(true);
                }}
                onShouldStartLoadWithRequest={(event)=>{
                    if (event.navigationType === 'click') {
                        if (!event.url.match(/(google\.com\/*)/) ) {
                            Linking.openURL(event.url)
                            return false
                        }
                        return true
                    }
                    else{
                        return true;
                    }
                }}
                onLoadEnd={(syntheticEvent) => {
                    setLoading(false);
                }}
            />
            {isLoadong && (
                <ActivityIndicator
                color="#234356"
                size="large"
                style={styles.loading}
                />
            )}
            </SafeAreaView>
          );
      }
    const styles = StyleSheet.create({
      safeArea: {
      flex: 1,
      backgroundColor: '#234356'
    },
    loading: {
      position: 'absolute',
      left: 0,
      right: 0,
      top: 0,
      bottom: 0,
      alignItems: 'center',
      justifyContent: 'center'
    },
    container: {
      flex: 1,
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
    },
  });
Run Code Online (Sandbox Code Playgroud)