还可以通过记录前后两次的滚动距离来判断每次滑动的方向
/**
* 说明:这里是垂直的滚动视图,如果采用水平的滚动视图需要更改相关变量
*
* 注意点:安卓中调用scrollTo方法不会,触发ScrollView的onMomentumScrollEnd方法
* 并且不要在onscroll中,将滚动距离存在state中,会产生巨大误差
*/
import React, {Component} from 'react';
import {
StyleSheet,
View,
Text,
ScrollView,
ToastAndroid,
Button
} from 'react-native';
//ScrollView滚动距离,每次滚动后对他进行更新
var scrollY;
//子组件高度
const childHeight=200;
export default class ScrollViewDemo extends Component {
state = {
data:['第1个', '第2个', '第3个', '第4个', '第5个', '第6个', '第7个', '第8个', '第9个', '第10个'],
}
/*用来存储ScrollView*/
_scroll;
render() {
return (
<View style={{flex:1}}>
<Button title="滚动视图算法测试" />
<Button title='滚动到y:100的位置' onPress={()=>{
this._scroll.scrollTo({y:100});
}}/>
<Button title='滚动到末尾' onPress={()=>{
this._scroll.scrollToEnd();
}}/>
{/*onLayout将ScrollView组件的height、width放进state里*/}
<ScrollView
onLayout={({nativeEvent:e})=>{this.setState({scrollHeight:e.layout.height,scrollWidth:e.layout.width})}}
ref={(scroll)=>this._scroll = scroll}
style={{borderColor:'red',borderWidth:2}}
contentContainerStyle={{paddingLeft:20,paddingRight:20}}
keyboardDismissMode='on-drag'
keyboardShouldPersistTaps='never'
showsVerticalScrollIndicator={true}
scrollEnabled={true}
pagingEnabled={true}
horizontal={false}
onMomentumScrollEnd={(e)=>{
console.log("onMomentumScrollEnd");
//计算出ScrollView滚动到底部时,所需的滚动距离
const toBottom = childHeight * this.state.data.length - this.state.scrollHeight;
if(scrollY == 0 || scrollY == toBottom){
console.log("底部或者顶部");
}else{
let index = Math.floor(scrollY / childHeight);
//具体滑动位置可更改,此处是刚好显示出一个完整子组件
this._scroll.scrollTo({y:index * childHeight});
}
}
}
onContentSizeChange={(contentWidth, contentHeight)=>{
var msg = 'onContentSizeChange:'+contentWidth+','+contentHeight;
ToastAndroid.show(msg,ToastAndroid.SHORT);
}}
onScroll={(e)=>{
console.log("onscroll");
scrollY = e.nativeEvent.contentOffset.y;
}}>
{
this.state.data.map((item, index) => {
var color = index * 23 + 10;
return <Text style={[styles.text,{backgroundColor:color}]}>{item}</Text>
})
}
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
text: {
height: childHeight,
textAlign: 'center',
textAlignVertical: 'center',
color: 'red',
fontSize: 30
}
})