首页 > 解决方案 > react-native-webview 为什么 goBack() 方法不起作用?

问题描述

我在 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,
  },
});

WebView 组件可以很好地加载网站(google.co.uk),但我无法让导航正常工作。我只是想创建一个后退按钮,它允许用户导航回他们在 WebView 中查看过的其他页面,如果他们已经返回并想要前进,则前进。

现在我正试图让后退按钮工作。我加载应用程序,然后导航到 WebView 上的不同页面。当按下返回按钮时,会产生以下错误:

TypeError: _reactNativeWebview.WebView.goBack 不是函数(在 '_reactNativeWebview.WebView.goBack()' 中,'_reactNativeWebview.WebView.goBack' 未定义)

根据文档的 goBack() 方法存在:

回去()

发现了这一点,但它正在实现一个基于类的组件,因此我无法轻松地将建议映射到我的功能组件中,此外,我认为解决方案在拦截导航时过于矫枉过正,我相信我想要实现的目标应该是更简单,但我无法让基本导航在 WebView 上工作(即返回和前进到以前查看的页面)。

标签: react-nativereact-native-androidexporeact-native-iosreact-native-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,
  },
});

此参考将帮助您调用webview 模块文档中提到的任何参考函数。享受!


推荐阅读