【问题标题】:FlatList scroll after adding new element添加新元素后 FlatList 滚动
【发布时间】:2017-10-31 09:47:47
【问题描述】:

我正在使用 ReactNative 的 FlatList 组件,它运行良好。现在我想在用户输入新元素/评论时将其滚动到底部。

<FlatList style={styles.commentList}
    data={commentList}
    keyExtractor={(item, index) => index}
    renderItem={this.renderRow.bind(this)}
/>

现在,每当用户输入新评论时,commentList 都会更新,FlatList 也会刷新,但我想滚动到底部,以便用户可以阅读最新发布的评论。

【问题讨论】:

  • 你试过scrollToIndex吗?在此处查看文档facebook.github.io/react-native/docs/…
  • @Srijith 是的,我也尝试过this.commentRef.scrollToIndex({ animated: true, index: 10 }),但不知何故也没有奏效。
  • 如果能在这里分享点心就好了snack.expo.io

标签: android ios react-native react-native-flatlist


【解决方案1】:

看看这个: 这不是我的解决方案,但我开始使用这种方法。

https://exp.host/@xavieramoros/snack-SyN4FJikz 源代码: https://github.com/xavieramoros/flatlist-initialScrollIndexIssue/blob/master/App.js 世博会 22 - RN 0.49

非常感谢https://expo.io/@xavieramoros

已编辑:如果您只想滚动到底部,则可以在新 RN 中使用 scrollToEnd (https://facebook.github.io/react-native/docs/flatlist.html#scrolltoend)。 像使用它一样

<FlatList
        ref={ (ref) => { this.flatList = ref; }}
        data={this.data}
        renderItem={ this.renderItem }
        keyExtractor={ this.keyExtractor}
        onScroll={ this.scrollToEnd}
      />
    ......

在你的方法中

scrollToEnd = () => {
    const wait = new Promise((resolve) => setTimeout(resolve, 0));
    wait.then( () => {
        this.flatList.scrollToEnd({ animated: true });
    });
}

【讨论】:

  • 欢迎提供解决方案的链接,但请确保您的答案在没有它的情况下有用:add context around the link 这样您的其他用户就会知道它是什么以及为什么会出现,然后引用最相关的内容您链接到的页面的一部分,以防目标页面不可用。 Answers that are little more than a link may be deleted.
  • 我自己在某种程度上使用了链接的答案,但由于每个问题的上下文可能不同,我只是发布了整个答案(链接)。至于您的情况,请确保您已为可变索引高度实现了 getItemLayout。 (facebook.github.io/react-native/docs/…) 而且这个问题真的很笼统,如果你想要一些具体的答案,那么请发布一个完整的问题和更多的代码!谢谢。
【解决方案2】:

尝试 FlatList 与倒置道具为真。 (还不如反转数据数组) 由于 flatlist 被倒置,新数据被添加到第一个位置,并且由于这个更新 flatlist 自动滚动到第一个位置,在你的情况下是底部位置

【讨论】:

  • 它会在末尾或第一个元素显示最近/新元素吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 2014-09-10
  • 1970-01-01
  • 1970-01-01
  • 2018-05-23
相关资源
最近更新 更多