首页 > 解决方案 > React Native Webview - 如何实现滚动到顶部按钮?

问题描述

React Native WebView 似乎不支持scrollTo({x: 0, y: 0, animated: true})并且不确定如何实现滚动到顶部按钮。

这就是我的 web 视图在渲染中的样子。

<WebView
  source={{ uri: "https://google.com/" }}
  refProps={(webView) => { this.webView.ref = webView; }}
/>

<TouchableOpacity onPress={() => this.webView.ref.scrollTo({x: 0, y: 0})} /> // How to make this work?
  <Text>Scroll to Top</Text>
</TouchableOpacity>

此代码不起作用,因为scrollToReact Native Webview 不支持。我该如何解决这个问题?

标签: javascriptreact-nativereact-native-webview

解决方案


const onPressButton = () => {
    webViewRef.current.injectJavaScript(`
      window.scroll({
        top: 0, 
        left: 0, 
        behavior: 'smooth'
      })
    `);
};

您可以在按下按钮时使用此代码。


推荐阅读