Skip to content

Instantly share code, notes, and snippets.

@fasthold
Created April 3, 2023 06:29
Show Gist options
  • Save fasthold/e763907b1881f9071b18dc95f93599ba to your computer and use it in GitHub Desktop.
Save fasthold/e763907b1881f9071b18dc95f93599ba to your computer and use it in GitHub Desktop.
React Native 加载webview网页时,后退按钮定义为网页返回而不是整体screen返回
import { SafeAreaView, StyleSheet, Text, View, ActivityIndicator, BackHandler } from 'react-native';
import React, { useRef, useState, useEffect } from 'react';
import { WebView } from 'react-native-webview';
const Contents = ({ navigation }) => {
const webViewRef = useRef()
const [isLoading, setLoading] = useState(false);
const handleBackButtonPress = () => {
if (webViewRef.current.canGoBack) {
webViewRef.current.goBack();
return true; // PREVENT DEFAULT BEHAVIOUR (EXITING THE APP)
}
return false;
}
useEffect(() => {
BackHandler.addEventListener("hardwareBackPress", handleBackButtonPress)
return () => {
BackHandler.removeEventListener("hardwareBackPress", handleBackButtonPress)
};
}, []);
return (
<SafeAreaView style={{ flex: 1 }
}>
<WebView
ref={webViewRef}
originWhiteList={['*']}
source={{ uri: 'https://www.qq.com' }}
startInLoadingState
allowsBackForwardNavigationGestures
style={{ marginTop: 20 }}
renderLoading={() => (
<View style={{ flex: 1, alignItems: 'center' }}>
<ActivityIndicator size="large" />
</View>
)}
onNavigationStateChange={navState => { webViewRef.current.canGoBack = navState.canGoBack }}
/>
</SafeAreaView >
);
};
export default Contents;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment