在我的应用程序中,ScrollToIndex无法按预期工作。这是我的代码。
getItemLayout = (data, index) => (
{ length: 50, offset: 50 * index, index }
)
scrollToIndex = () => {
if(this.flatListRef != null){
setTimeout(() => this.flatListRef.scrollToIndex({animated: false, index: 5}), 200)
}
// this.flatListRef.scrollToIndex({animated: true, index: 5});
}
// render post
renderPost({ item, index }) {
return (
<Post
post={item}
likeIsLoading={
item.shareId === this.props.likeLoadingPostId &&
this.props.likeIsLoading
}
likeCount={item.likeCount > 0 ? item.likeCount : ""}
likeIcon={item.hasLiked === 1 ? LikeActive : LikeInactive}
name={item.hasLiked === 1 ? "like-active" : "like-inactive"}
onIconClick={payload => this.onIconClick(payload)}
/>
);
}
// render
render() {
let { posts, featuredWorkouts, mainFeedIsLoading } = this.props;
let mainFeedData = (
<View>
<View style={{ marginBottom: 5 }}>
<SwiperContainer featuredWorkouts={featuredWorkouts} />
</View>
<FlatList
ref={(ref) => { this.flatListRef = ref; }}
data={posts}
extraData={[posts, mainFeedIsLoading, featuredWorkoutsAreLoading]}
renderItem={(item, index) => this.renderPost(item, item.shareId)}
getItemLayout={this.getItemLayout}
// initialScrollIndex={4}
keyExtractor={item => item.shareId}
/>
</View>
);
if (mainFeedIsLoading) {
mainFeedData = (
<View style={styles.screenLoader}>
<ScreenLoader color="lightblue" size="large" />
</View>
);
}
return (
<View>
<Button
onPress={() => this.scrollToIndex()}
title="Tap to scrollToIndex"
color="darkblue"
/>
<ScrollView>{mainFeedData}</ScrollView>
</View>
);
}
我尝试了在互联网上提出的建议,但没有一个有效。我在这做错了什么?我怎样才能实现我的目标?例如,我想在单击按钮时移动到第5个索引。