React Native 双向无限滚动: 极致流畅体验的革新者
import React from 'react';
import {
View,
StyleSheet,
Dimensions,
Animated,
Platform,
ScrollView,
} from 'react-native';
const { width: screenWidth } = Dimensions.get('window');
export default class InfiniteScrollView extends React.Component {
scrollX = new Animated.Value(0);
render() {
const { data, renderItem } = this.props;
return (
<ScrollView
horizontal
pagingEnabled
scrollEventThrottle={1}
onScroll={Animated.event(
[{ nativeEvent: { contentOffset: { x: this.scrollX } } }],
{ useNativeDriver: true }
)}
showsHorizontalScrollIndicator={false}
contentContainerStyle={styles.container}
snapToInterval={screenWidth}
decelerationRate="fast"
>
{data.map((item, index) => (
<View key={index} style={styles.item}>
{renderItem(item, index)}
</View>
))}
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flexGrow: 0, // Prevents Android from creating extra space at the end
},
item: {
width: screenWidth,
},
});
这个代码实例展示了如何在React Native中实现一个双向无限滚动的ScrollView组件。它使用Animated API来实现平滑的滚动动画,并且可以通过传递数据和渲染项的方法来自定义每个滚动项的内容。
评论已关闭