Android上的React原生Webview制作后退按钮返回

jtoj6r0c  于 2022-11-25  发布在  React
关注(0)|答案(3)|浏览(206)

当我点击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',
  },
});
5rgfhyps

5rgfhyps1#

在react-native-webview库中有内置的goBack()方法,您可以使用API方法实现webview的向后导航。
为此,您必须获取react-native-webview组件的引用,并从引用对象调用方法。
此外,您还可以将侦听器放在Android本地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',
    },
  });
sxpgvts3

sxpgvts32#

首先添加ref以访问webview,如下所示:

<WebView
    ref={WEBVIEW_REF}

则要访问硬件后退按钮,您可以使用以下命令:

import { BackHandler } from 'react-native';

constructor(props) {
    super(props)
    this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
}

componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}

componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
}

handleBackButtonClick() {
    this.refs[WEBVIEW_REF].goBack();
    return true;
}

handleBackButtonClick中,您可以返回webview并添加this.refs[WEBVIEW_REF].goBack();。我希望这对您有帮助:)

8ehkhllq

8ehkhllq3#

下面是一个使用React's State的魔力的简单解决方案。
希望这对你有帮助。

import React, { useRef, useState } from 'react'

export default function Component () {

    // This is used to save the reference of your webview, so you can control it
    const webViewRef = useRef(null);

    // This state saves whether your WebView can go back
    const [webViewcanGoBack, setWebViewcanGoBack] = useState(false);

    const goBack = () => {

        // Getting the webview reference
        const webView = webViewRef.current
        
        if (webViewcanGoBack)
            // Do stuff here if your webview can go back 
        else
            // Do stuff here if your webview can't go back 
    }

    return (        
        <WebView
            source={{ uri: `Your URL` }}
            ref={webViewRef}
            javaScriptEnabled={true}
            onLoadProgress={({ nativeEvent }) => {
                // This function is called everytime your web view loads a page
                // and here we change the state of can go back
                setWebViewcanGoBack(nativeEvent.canGoBack)
            }}
        />
    )
}

相关问题