React-Native ScrollView,自动滚动行为

我正在尝试在ScrollView中实现自动滚动,但由于某种原因,我无法想到正确的方式来实现,例如,如果我添加一个项目,并且contentSize超出了ScrollView的宽度,则应该滚动到最后,如果我删除一个项目,并且contentSize小于ScrollView的宽度,则应滚动到开头。

这是我到目前为止所拥有的

    <ScrollView
      horizontal
      showsHorizontalScrollIndicator={false}
      ref={(scrollView) => {
        this.scrollView = scrollView;
      }}
      onLayout={(e) => {
        this.layoutWidth = e.nativeEvent.layout.width;
      }}
      onContentSizeChange={(contentWidth,contentHeight) => {
        this.scrollView.scrollTo({
          x: contentWidth > this.layoutWidth ? contentWidth + this.layoutWidth - width : 0,y: 0,animated: true,});
      }}>
      {contacts.map((contact) => (
        <SelectedContacsItem
          contact={contact}
          onRemoveContactPress={onRemoveContactPress}
          key={contact.id}
        />
      ))}
    </ScrollView>

这不适用于删除项目的过程,在最后一个项目上(当内容小于视图时)它将内容移动到随机位置,我添加了onScroll属性并从那里观看了日志,似乎contentOffSet是一个问题,因为它具有随机值(有时为负数,有时为大数),不确定如何解决。

gaoxizhangya 回答:React-Native ScrollView,自动滚动行为

我一周前做了这样的事情,在这种情况下,我建议您(像我一样)放弃ScrollViewmap

<FlatList
   ref={ref => this.flatListRef = ref}
   horizontal
   data={contact}
   extraData={this.state}
   keyExtractor={(item,index) => index}
   renderItem={({ item,index }) => <SelectedContacsItem
      contact={item}
      onRemoveContactPress={onRemoveContactPress}
      key={item.id}
      index={index}
    />}
/>

函数onRemoveContactPress使用scrollToIndex属性处理滚动(不要忘记传递index

onRemoveContactPress = (index) => {
    this.flatListRef.scrollToIndex({ animated: true,index: index });
}
  • 如果scrollToIndex没有滚动到正确的索引,请尝试将索引更改为其他内容(与此同时“播放”)
  • 例如,在我的例子中,
  • 是在RTL方向上的,所以它看起来像这样:index: this.state.contact.length - index - 1
本文链接:https://www.f2er.com/3165359.html

大家都在问