乐闻世界logo
搜索文章和话题

Get current scroll position of ScrollView in React Native

1个答案

1

In React Native, to obtain the current scroll position of ScrollView, we can use the onScroll event to monitor scrolling activity and, along with the scrollEventThrottle property, control how frequently the event is triggered. Additionally, we need to utilize a reference (ref) to ensure access to the ScrollView component instance.

Here is a specific example demonstrating how to implement this:

First, set up the onScroll event handler within the ScrollView component to retrieve scroll position information via the event parameter. Also, configure the scrollEventThrottle property, which specifies the frequency at which the scroll event handler is invoked, measured in milliseconds.

javascript
import React, { useRef } from 'react'; import { ScrollView, Text, View, StyleSheet } from 'react-native'; const ScrollExample = () => { const scrollViewRef = useRef(null); const handleScroll = (event) => { const scrollPosition = event.nativeEvent.contentOffset.y; console.log('Current scroll position:', scrollPosition); }; return ( <View style={styles.container}> <ScrollView ref={scrollViewRef} onScroll={handleScroll} scrollEventThrottle={16} // Set to 16 milliseconds, meaning the handler is invoked approximately 60 times per second (1000ms / 16ms ≈ 60) style={styles.scrollViewStyle} > {Array.from({ length: 50 }, (_, index) => ( <Text style={styles.textStyle} key={index}> Item {index + 1} </Text> ))} </ScrollView> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, paddingTop: 50, }, scrollViewStyle: { marginHorizontal: 20, }, textStyle: { marginVertical: 20, fontSize: 20, textAlign: 'center', }, }); export default ScrollExample;

In this example, when the user scrolls the screen, the handleScroll function is triggered, and the vertical scroll position can be accessed using the event.nativeEvent.contentOffset.y property. Setting scrollEventThrottle to 16 ensures the handler is called approximately 60 times per second (1000ms / 16ms ≈ 60), which balances performance and responsiveness.

By implementing this approach, we can retrieve the current scroll position within ScrollView in real-time and perform corresponding actions, such as triggering specific animations or updating the state.

2024年6月29日 12:07 回复

你的答案