【问题标题】:FlatList React-Native: How i can focus scroll in the specific list itemFlatList React-Native:我如何在特定列表项中聚焦滚动
【发布时间】:2019-02-13 04:19:40
【问题描述】:

上下文:

我正在使用“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);
}

【问题讨论】:

  • 在scrollToOffset中设置animated: false
  • @ShashinBhayani 谢谢你的评论。我已经用过这种方式,但是这更突然,这就是我发布我的问题的原因。
  • 我不知道如何避免动画,但是,您可以在动画发生时放置一个 ActivityIndi​​cator(加载警报)以“隐藏”并锁定用户的交互,直到当月设置。
  • @MtgKhaJeskai 谢谢你的评论。是的,这就是我现在正在做的事情,是我想到的第一个解决方案。除了我想使用“FlatList”或“ScrollView”属性来解决这个请求。
  • 试试我的回答。

标签: javascript reactjs listview react-native scrollview


【解决方案1】:

使用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}
  />

【讨论】:

  • 感谢您的帮助,尽管此语句需要 getItemLayout() 才能正常工作。在生产环境中也需要进行必要的测试,因为在开发环境中过渡非常缓慢。
  • 很好,它对你有用吗?如果是,请将此问题设置为正确!问候
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
相关资源
最近更新 更多