我希望实现ScrollView的无限滚动,可以向两个方向滚动并且数据应该是动态加载的。
我正在使用SectionList组件进行列表操作。我已经实现了正向无限滚动,也就是说,如果用户向下滚动,数据将自动附加到列表中。
为此,我使用了onMomentumScrollEnd事件。当用户停止滚动时,如果滚动方向向上,则在结尾处追加数据;如果滚动方向向下,则在顶部追加数据。
现在的问题是:当我在列表顶部添加数据时,它会使当前列表数据全部向后移动。即使更新数据,我也不想移动当前列表。有没有办法解决这个问题?
以下是我的代码:
我正在使用SectionList组件进行列表操作。我已经实现了正向无限滚动,也就是说,如果用户向下滚动,数据将自动附加到列表中。
为此,我使用了onMomentumScrollEnd事件。当用户停止滚动时,如果滚动方向向上,则在结尾处追加数据;如果滚动方向向下,则在顶部追加数据。
现在的问题是:当我在列表顶部添加数据时,它会使当前列表数据全部向后移动。即使更新数据,我也不想移动当前列表。有没有办法解决这个问题?
以下是我的代码:
import React, {Component} from 'react';
import {
Text,
View,
StyleSheet,
SectionList,
} from 'react-native';
import CardComponent from './CardComponent'
export default class Schedule extends Component {
constructor(props) {
super(props);
this.state = {
sectionData: [],
loading: false,
}
this.contentOffsetY = 0;
this._onScroll = this._onScroll.bind(this)
}
componentDidMount() {
this.setState({ sectionData: this.props.data })
}
renderItem = ({item}) => (
<CardComponent
data={item}
key={item}
/>
);
renderDateSeparator(text) {
return (
<Text style={{
paddingVertical: 15,
fontSize: 14,
flex: 1,
textAlign: 'center',
textAlignVertical: 'center',
}}>
{text}
<Text>
)
}
_onScroll(e){
let contentOffset = e.nativeEvent.contentOffset.y;
this.contentOffsetY < contentOffset ? this.loadMoreOnBottom() : this.loadMoreOnTop();
this.contentOffsetY = contentOffset;
}
loadMoreOnTop() {
this.setState({ lodaing: true });
// code to append data on top of list
this.setState({ lodaing: false });
}
loadMoreOnBottom() {
// code to append data at bottom of list
}
render() {
const sectionData = this.state.sectionData;
return(
<View style={{flex: 1}}>
<SectionList
onMomentumScrollEnd={this._onScroll}
automaticallyAdjustContentInsets={false}
itemShouldUpdate={false}
renderItem={this.renderItem}
renderSectionHeader={({section}) => this.renderDateSeparator(section.date)}
sections={sectionData}
stickySectionHeadersEnabled={false}
refreshing={this.state.loading}
onRefresh={() => this.loadMoreOnTop()}
onEndReachedThreshold={0.3}
onEndReached={() => this.loadMoreOnBottom()}
keyExtractor={(item) => item.key}
/>
</View>
)
}
}
提前感谢。