简体   繁体   中英

React Native Webview: How to trigger function once on onScroll?

I want to trigger the reload function on scroll position. I set below code to trigger reload when contentOffset.y is smaller than -180 but it's being triggered multiple times as contentOffset.y's position keeps changing.

How do I make sure that reload is only triggered once?

_onScroll = (event) => {
  if (event.nativeEvent.contentOffset.y < -180) {
    this.webView.ref && this.webView.ref.reload();
    console.log("Triggered multiple times as event.nativeEvent.contentOffset.y is keep changing")
  }
};

Here is the WebView where it gets the scroll position.

<WebView
  bounces={true}
  onScroll={this._onScroll}
/>

You need a way to tell your component that you have already run the scroll reload, then only run the reload function if it hasn't been run before. The best way to do this is in the component's state:

_onScroll = (event) => {
  if (event.nativeEvent.contentOffset.y < -180) {
    !this.state.scrollReloaded && this.webView.ref && this.webView.ref.reload();
    this.setState({ scrollReloaded: true });
  }
};

The above solution works but is not as performant; _onScroll will still get called every time we scroll. This gives you extra flexibility but is tougher on the CPU. For slightly better performance you can add this:

<WebView
  bounces={true}
  onScroll={e => !this.state.scrollReloaded && this._onScroll(e)}
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM