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

Get current scroll position of ScrollView in React Native

4 个月前提问
3 个月前修改
浏览次数45

1个答案

1

在React Native中,要获取ScrollView的当前滚动位置,我们可以使用onScroll事件来监听滚动,并结合scrollEventThrottle属性来控制事件触发的频率。此外,我们还需要使用一个引用(ref)来确保我们可以访问到ScrollView组件的实例。

下面是一个具体的例子来说明如何实现:

首先,我们需要在ScrollView组件中设置onScroll事件处理器,并通过event参数获取滚动位置信息。我们还需要设置scrollEventThrottle属性,这个属性决定了滚动事件处理函数被调用的频率,单位是毫秒。

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('当前滚动位置:', scrollPosition); }; return ( <View style={styles.container}> <ScrollView ref={scrollViewRef} onScroll={handleScroll} scrollEventThrottle={16} // 这里设置为16毫秒,意味着每秒最多处理60次滚动事件(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;

在这个例子中,当用户滚动屏幕时,handleScroll函数会被调用,我们可以通过event.nativeEvent.contentOffset.y属性来访问垂直方向上的滚动位置。我们设置了scrollEventThrottle为16,这意味着函数调用的频率为大约每秒60次,这个设置旨在平衡性能和响应速度。

通过这种方式,我们可以实时获取ScrollView中的当前滚动位置,并进行相应的处理,例如触发特定的动画或者更新状态。

2024年6月29日 12:07 回复

你的答案