【问题标题】:Prevent FlatList scrolling when new items are added添加新项目时防止 FlatList 滚动
【发布时间】:2019-06-12 11:27:32
【问题描述】:

我在我的聊天应用程序中反转了垂直 FlatList,它在底部显示最新消息,在顶部显示最旧消息(与所有其他聊天应用程序一样)
问题是当我想将新消息添加到列表底部时,FlatList 会自动跳转到列表底部!
我所需要的只是防止在这种情况下滚动

这是我的FlatList

<FlatList
  inverted
  style={{flex: 1}}
  data={this.state.data}
  keyExtractor={(item, index) => item.id}
  renderItem={this.renderItem}
/>

这是将最新消息添加到列表的代码

const data = [ ...newMessages, ...this.state.data ];
this.setState({ data });

【问题讨论】:

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


【解决方案1】:

您的案例看起来很简单,但您要在顶部添加新消息,然后使用 inverted 标志将其反转到最后一个位置

可以删除inverted标志并添加新项目,最后只需const data = [...this.state.data, ...newMessages];

<FlatList
  style={{flex: 1}}
  data={this.state.data}
  keyExtractor={(item, index) => item.id}
  renderItem={this.renderItem}
/>

const data = [...this.state.data, ...newMessages];
this.setState({ data });

我希望这会奏效

【讨论】:

  • 我需要在FlatList 的两侧添加新项目,正如我在问题中提到的那样:在底部显示最新消息,在顶部显示最旧消息(与所有其他聊天应用程序一样)
【解决方案2】:

您应该使用解决方法来实现此目的。如果您查看 FlatList 的文档(它扩展了 ScrollView 的道具),您会发现您需要做的就是将 scrollEnabled 道具设置为 false 以禁用滚动。您选择如何以及在何处执行此操作将取决于您,因为您并没有真正发布很多代码。处理这个问题的一个简单方法是使用 state:

<FlatList
  ...
  scrollEnabled={this.state.scrollEnabled}
/>

在您的情况下,您可以在加载新数据时更改状态,并在呈现时将其更改回来。

Github 上有一个关于这个案例的公开issue

【讨论】:

  • 感谢您的关注,但这不起作用,即使scrollEnabled 设置为false,添加新项目后FlatList 仍会自动向下滚动
【解决方案3】:

把它放在视图中

<FlatList
  data={this.state.data}
      ref={ref => {
        this.flatListRef = ref;
      }}
      initialScrollIndex={0}
      keyExtractor={item => item.id}
      extraData={this.state.refresh}
      renderItem={({item, index}) => {
        // animation={animation}
        return (
          <ListItem
            inAnimation={inAnimation}
            outAnimation={outAnimation}
            duration={duration}
            easing={easing}
            isDeleted={item._isDeleted}
            id={item.id}
            item={item}
          />
        );
      }}
    `/>`

在函数中运行它

this.flatListRef.scrollToIndex({
       animated: true,
       index: nextProps.indexScroll})

  });

【讨论】:

    猜你喜欢
    • 2012-04-08
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多