如何在React Native中刷新Web视图?

rlcwz9us  于 2022-12-14  发布在  React
关注(0)|答案(6)|浏览(289)

我在选项卡A上有一个Web视图,在选项卡B上有一个todolist平面列表。如果用户向选项卡B上的平面列表添加一个条目,我希望选项卡A的Web视图刷新。
在webview控件https://facebook.github.io/react-native/docs/webview.html上找不到任何.refresh()reload()方法
有什么想法如何完成这一点?

hmae6n7t

hmae6n7t1#

您可以设置web视图的键

key={this.state.key}

然后通过更新状态来重新加载它

this.setState({ key: this.state.key + 1 });
rryofs0p

rryofs0p2#

我通过执行以下操作重新加载WebView

render() {
  let WebViewRef;
  return (
    <View style={Style1.container}>
      <WebView
        ref={WEBVIEW_REF => (WebViewRef = WEBVIEW_REF)}
        source={{ uri: this.state.site }}
        renderLoading={this.ActivityIndicatorLoadingView}
        startInLoadingState={true}
      />
      <Button title="Reload Me!" onpress={() => { WebViewRef && WebViewRef.reload(); }} />
    </View>
  )
}

在这段代码中,我首先声明引用变量WebViewRef,然后将其赋值给WebView作为ref={WEBVIEW_REF => (WebViewRef = WEBVIEW_REF)},然后调用reload()的引用作为()=>{ WebViewRef && WebViewRef.reload();}

jum4pzuy

jum4pzuy3#

react-native-community/react-native-webview组件在ref上有一个.reload()方法。

const webViewRef = useRef();
// ...
return (
    <WebView ref={(ref) => webViewRef.current = ref} ... />
)
// ...

然后,您可以使用以下命令重新加载:

webViewRef.current.reload();
kzipqqlq

kzipqqlq4#

最后我使用了一个伪查询参数来表示Web视图的刷新:
在Tab B中,我分派了一个改变全局状态中“latestItemId”的更改。在Tab A中,我使用了mapStateToProps,它Map到render方法中的<WebView source={{uri:URL?latestItemId=${latestItemId}}} />。这会使它认为这是一个新的url并重新加载它。

zynd9foi

zynd9foi5#

重新加载在我这边不起作用。
如果你想在焦点改变时刷新,你可以使用react navigation的钩子useFocusEffect,在卸载时清除webview中使用的URL。然后在初始化时你需要再次设置它。可能使用一个useState。

useFocusEffect(
    useCallback(() => {
      setUrl(url!);
      return () => {
        setUrl(undefined);
      };
    }, [url]),
  );
xmjla07d

xmjla07d6#

在我的例子中,我有source={{html}},所以refresh()在那种情况下不起作用。但是,在我的例子中,我仍然能够注入javascript,所以我可以设置一些属性,特别是document.styles.body.color,以匹配黑暗和光明模式。

const fg = colorScheme === "light" ? "black" : "white";
  const webViewRef = createRef<WebView>();
  useEffect(() => {
    webViewRef.current?.injectJavaScript(`
      document.body.style.color='${fg}';
      true
    `);
  }, [fg]);

...
  <WebView
    ref={webViewRef}
    originWhitelist={["*"]}
    style={{
      height: 200,
      backgroundColor: "transparent",
    }}
    onMessage={() => {}}
    javaScriptEnabled={true}
    injectedJavaScript={`
      document.body.style.color='${fg}';
      true;`}
    source={{ html }}
  />

相关问题