Gar*_*ary 2 react-native react-native-android react-native-ios expo react-native-webview
我在 Expo 中有一个简单的 React Native 项目,它使用react-native-webview启动一个网站。
这是源代码:
import React from "react";
import { StyleSheet, View, SafeAreaView } from "react-native";
import { AntDesign } from "@expo/vector-icons";
import { WebView } from "react-native-webview";
export default function App() {
const goback = () => {
WebView.goBack();
};
return (
<SafeAreaView>
<WebView source={{ uri: "https://google.co.uk" }} />
<View style={styles.navbar}>
<View style={styles.forward}>
<AntDesign name="right" size={25} color="grey" />
</View>
<View style={styles.back}>
<AntDesign name="left" size={25} color="grey" onPress={goback} />
</View>
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
navbar: {
height: 40,
width: "100%",
flexDirection: "row-reverse",
paddingTop: 6,
backgroundColor: "#fefefe",
borderTopColor: "grey",
borderTopWidth: 1,
},
back: {
width: 50,
height: 50,
marginRight: 10,
},
forward: {
width: 50,
height: 50,
},
});
Run Code Online (Sandbox Code Playgroud)
WebView 组件可以正常加载网站 (google.co.uk),但我无法使导航正常工作。我只是想创建一个后退按钮,允许用户导航回他们在 WebView 中查看过的其他页面,如果他们已经返回并想要前进,则前进。
现在我正在尝试让后退按钮工作。我加载应用程序,然后导航到 WebView 上的不同页面。当按下后退按钮时,会产生以下错误:
TypeError: _reactNativeWebview.WebView.goBack 不是一个函数(在 '_reactNativeWebview.WebView.goBack()','_reactNativeWebview.WebView.goBack' 中是未定义的)
根据文档的 goBack() 方法存在:
我发现了这个,但它正在实现一个基于类的组件,所以我无法轻松地将建议映射到我的功能组件中,此外,我认为该解决方案在拦截导航时太过分了,我相信我想要实现的目标应该更简单,但我无法在 WebView 上使用基本导航(即返回和前进到以前查看的页面)。
你提到的一切都是正确的加里。您唯一需要更改的是调用goBack函数的方式。goBack 不是组件的直接功能,您需要传递对 WebView 组件的引用才能获得此功能。在您的情况下,您可以按如下方式更改组件以使其正常工作:-
import React, { useRef } from "react";
import { StyleSheet, View, SafeAreaView } from "react-native";
import { AntDesign } from "@expo/vector-icons";
import { WebView } from "react-native-webview";
export default function App() {
const webViewRef = useRef(null)
const goback = () => {
webViewRef.current.goBack();
};
return (
<SafeAreaView>
<WebView ref={webViewRef} source={{ uri: "https://google.co.uk" }} />
<View style={styles.navbar}>
<View style={styles.forward}>
<AntDesign name="right" size={25} color="grey" />
</View>
<View style={styles.back}>
<AntDesign name="left" size={25} color="grey" onPress={goback} />
</View>
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
navbar: {
height: 40,
width: "100%",
flexDirection: "row-reverse",
paddingTop: 6,
backgroundColor: "#fefefe",
borderTopColor: "grey",
borderTopWidth: 1,
},
back: {
width: 50,
height: 50,
marginRight: 10,
},
forward: {
width: 50,
height: 50,
},
});
Run Code Online (Sandbox Code Playgroud)
此参考将帮助您调用webview 模块文档中提到的任何参考函数。享受!
归档时间: |
|
查看次数: |
4267 次 |
最近记录: |