Get current scroll position of ScrollView in React Native

后端 未结 11 1461
遇见更好的自我
遇见更好的自我 2020-11-27 11:10

Is it possible to get the current scroll position, or the current page of a component in React Native?

So something like:

<         


        
相关标签:
11条回答
  • 2020-11-27 11:25

    Use

    <ScrollView 
     onMomentumScrollEnd={(event) => this.getscrollposition(event)} 
     scrollEventThrottle={16}>
    

    Show Position

    getscrollposition(e) {console.log('scroll y ', e.nativeEvent.contentOffset.y);}
    
    0 讨论(0)
  • 2020-11-27 11:29

    If you wish to simply get the current position (e.g. when some button is pressed) rather than tracking it whenever the user scrolls, then invoking an onScroll listener is going to cause performance issues. Currently the most performant way to simply get current scroll position is using react-native-invoke package. There is an example for this exact thing, but the package does multiple other things.

    Read about it here. https://medium.com/@talkol/invoke-any-native-api-directly-from-pure-javascript-in-react-native-1fb6afcdf57d#.68ls1sopd

    0 讨论(0)
  • 2020-11-27 11:32

    As for the page, I'm working on a higher order component that uses basically the above methods to do exactly this. It actually takes just a bit of time when you get down to the subtleties like initial layout and content changes. I won't claim to have done it 'correctly', but in some sense I'd consider the correct answer to use component that does this carefully and consistently.

    See: react-native-paged-scroll-view. Would love feedback, even if it's that I've done it all wrong!

    0 讨论(0)
  • 2020-11-27 11:34

    Brad Oyler's answer is correct. But you will only receive one event. If you need to get constant updates of the scroll position, you should set the scrollEventThrottle prop, like so:

    <ScrollView onScroll={this.handleScroll} scrollEventThrottle={16} >
      <Text>
        Be like water my friend …
      </Text>
    </ScrollView>
    

    And the event handler:

    handleScroll: function(event: Object) {
      console.log(event.nativeEvent.contentOffset.y);
    },
    

    Be aware that you might run into performance issues. Adjust the throttle accordingly. 16 gives you the most updates. 0 only one.

    0 讨论(0)
  • 2020-11-27 11:37

    I believe contentOffset will give you an object containing the top-left scroll offset:

    http://facebook.github.io/react-native/docs/scrollview.html#contentoffset

    0 讨论(0)
  • 2020-11-27 11:41

    use of onScroll enters infinite loop. onMomentumScrollEnd or onScrollEndDrag can be used instead

    0 讨论(0)
提交回复
热议问题