【问题标题】:React native ScrollView resets positon on setStateReact native ScrollView 重置 setState 上的位置
【发布时间】:2020-04-18 17:20:42
【问题描述】:

我有一个带有按钮的ScrollView。我动态填充ScrollView。按下ScrollView 内的按钮后,我正在更改当前选定索引的状态,ScrollView 的位置正在重置。

<ScrollView
  ref={ref => {
    this._scrollview = ref;
  }}
  style={styles.scrollview}
  horizontal
  showsHorizontalScrollIndicator={false}
  snapToInterval={64}
  snapToAlignment="start"
  decelerationRate="fast"
  contentContainerStyle={{ paddingRight: 8, paddingLeft: 8 }}>
    {this._channels.map((item, index) =>
      <TouchableWithoutFeedback
        onLayout={event => {
          const layout = event.nativeEvent.layout;
          this._channelsPositions[index] = layout.x;
        }}
        key={item.userId}
        onPress={() => this._changeIndex(index)}>

        <Image
          source={{ uri: videos[index][0].channelThumbnails.high.url }}
          style={[styles.channelLogo, index == this.state.currentIndex ? { borderWidth: 2 } : {}]}
        />
      </TouchableWithoutFeedback>
    )}
</ScrollView>

_changeIndex = (newIndex: number) => {
  const { currentIndex } = this.state;
  if (newIndex == currentIndex) return;

  this.setState({
    currentIndex: newIndex
  });

  const newX = 16 + 48 * newIndex
  this._scrollview.scrollTo({
    x: 16 + 48 * newIndex,
    y: 0,
    animated: true
  })
}

按下按钮后,我希望ScrollView 移动到ScrollView 内此按钮的x 位置。 演示:https://streamable.com/gu1edy

更新: 在我将滚动视图替换为标题中的 Flatlist 后,我​​想我明白为什么会发生这种情况。但我仍然不知道如何解决它。所以行为是一样的,每次我按下滚动视图/平面列表的按钮/单元格/项目时,我都会重置滚动。 标题中带有嵌套平面列表的平面列表看起来如何

\ |CHANNEL ICON 0|CHANNEL ICON 1|CHANNEL ICON 2| ... \     header with flatlist         

\ FIRST ITEM IN FLATLIST WHICH CONTAINS VIDEO OF CHANNEL\  cell 0
\ SECOND ITEM IN FLATLIST WHICH CONTAINS VIDEO OF CHANNEL\ cell 1

...

所以在我点击频道图标后,所有主平面列表都会填充新数据,所以如果我理解正确,标题会重新渲染并重新填充新数据。那么有没有可能用 flatlist 更新标题,这样我的标题滚动保持在它的位置而不重置?

【问题讨论】:

  • 你试过 Flatlist 吗?
  • 还没有,但是如果我可以像snapToInterval={64} 那样进行分页并在我按下项目后自动滚动到索引,那么我想我会迁移到 Flatlist。但我不确定我可以将 FlatList 放在 FlatList 的标题中......
  • 是的,您可以在 flatlist 中使用 flatlist,因为它可以呈现您想要的项目。所以最好试一试。因为分页功能本身就是由 flatlist 提供的所以。
  • 是的,我用平面列表替换,同样的问题。看起来我总体上做错了..
  • 我确实有同样的问题。首先我使用 Flatlist,然后使用 Scrollview,它也有同样的问题。这很受伤。

标签: javascript typescript react-native scrollview react-native-flatlist


【解决方案1】:

您好,我已通过将 Scrollview 从我的部分功能组件移动到主功能组件屏幕来修复它。

例如你有两个函数:

  • 组件 RenderListProducts
  • 屏幕/页面产品

所以解决方案是在 RenderListProducts 中移动 Flatlist 的 Scrollview 并将其粘贴到屏幕/页面 Product 的内部。

试试看。如果您仍然有此问题,请在下面发表评论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    相关资源
    最近更新 更多