React Native Webview-如何实现滚动到顶部按钮?

时间:2020-07-07 00:14:23

标签: javascript react-native 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>

此代码不起作用,因为React Native Webview不支持scrollTo。我该如何解决?

1 个答案:

答案 0 :(得分:0)

尝试以下方法效果很好。

首先,从网络视图向网页发布一条消息(在您的本机应用程序的ode中插入以下行)

<TouchableOpacity onPress={() => this.webviewRef.postMessage(JSON.stringify({type: 'scrollToTop'}))} />
  <Text>Scroll to Top</Text>
</TouchableOpacity>

然后,听消息并触发滚动事件。

// JS script on your web page
   onMount(() => {
      if (typeof window !== 'undefined') {
        window.addEventListener("message", event => { 
          if (event.data) {
            let parsedEvent = JSON.parse(event.data);
            if (parsedEvent.type === 'scrollToTop') {
              animateScroll.scrollToTop(); 
            }
          }          
        });
   });
// I'm using animateScroll from "svelte-scrollto";

干杯。