首页 > 解决方案 > FlatList React-Native:我如何在特定列表项中聚焦滚动

问题描述

语境:

我正在使用“expo”处理“react-native”,并且我有一个倒置的“FlatList”,它在其中呈现从 1 月到 12 月的几个月的“数组”。

在此处输入图像描述

要求:

在将列表显示给用户之前,列表应该集中在当前月份。

现在的情况:

我正在使用“FlatList”“scrollToOffset”属性来执行此请求,当列表接收到“数据源”时,会自动触发“this.flatList.scrollToOffset”语句,列表动画滚动并聚焦特定项目。但是我有一个问题,这个动画是一个破坏用户体验的突然运动。

在此处输入图像描述

需要:

你能帮我找到解决这个问题的方法吗?我需要做同样的事情,但用户看不到滚动运动,他只应该看到项目集中。任何想法?

演示代码:

平面列表

<FlatList
  ref={ref => (this.flatList = ref)}
  inverted
  data={foods}
  keyExtractor={this.keyExtractor}
  renderItem={this.renderItem}
/>

聚焦项目的功能

handlePosition(id) {
  /* Item Size from FlatList */
  const itemSize = deviceWidth / 2 + 30;
  /* Id of the current month */
  const idCurrentItem = id;

  this.flatList.scrollToOffset({
    animated: true,
    offset: itemSize * idCurrentItem,
  });
}

语句在哪里调用 handlePosition 函数

componentDidMount() {
  this.handlePosition(this.props.months[2].id);
}

标签: javascriptreactjslistviewreact-nativescrollview

解决方案


使用FlatList组件的 initialScrollIndex 属性来排序要在其中启动 FlatList 的索引。

为此,您必须在 componentDidMount 或 componentWillMount 函数中计算渲染前的月份,您必须将月份(或索引)存储在状态中。然后,您将在 Flatlist 组件中访问此状态并将 initialscrollIndex 设置为它。

这里是 componentWillMount 函数的例子:

componentWillMount() {
...
  //assuming that we are on February will set index scroll to 1 being 0 January 
  //and being 3 March
  this.setState({monthToStart: 1});
}

initialScrollIndex 工作成功的必要声明

getItemLayout(data, index) {
  return (
    {
      length: yourItemHeightSize,
      offset: yourItemHeightSize * index,
      index
    }    
  );
}

这是 FlatList 组件添加新道具的示例:

  <FlatList
    ref={ref => (this.flatList = ref)}
    inverted
    data={foods}
    keyExtractor={this.keyExtractor}
    getItemLayout={(data, index) => this.getItemLayout(data, index)}
    renderItem={this.renderItem}
    initialScrollIndex={this.state.monthToStart}
  />

推荐阅读