javascript - FlatList react native : How i can focus scroll in the specific list item

标签 javascript reactjs listview react-native scrollview

上下文:

我正在使用“expo”处理“react-native”,我有一个倒置的“FlatList”,它呈现从一月到十二月的月份“数组”。

enter image description here

请求:

在列表显示给用户之前,列表应该聚焦在当月。

现状:

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

enter image description here

需要:

你能帮我找到解决这个问题的方法吗?我需要做同样的事情,但用户看不到那个滚动 Action ,他应该只看到聚焦的项目。 有什么想法吗?

演示代码:

平面列表

<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);
}

最佳答案

使用 FlatList 组件的 initialScrollIndex prop 来排序您想要开始 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 组件添加新 prop 的例子:

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

关于javascript - FlatList react native : How i can focus scroll in the specific list item,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54662444/

相关文章:

javascript - 定位元素以覆盖跨度

javascript - 无法使用 Froala 编辑器将图像上传到本地服务器

javascript - 传播 Redux Actions 在 mapDispatchToProps 中不起作用

javascript - 全局跟踪 Reactjs 页面和组件中的事件

java - 如何使用 ImageView 作为 OnClick 事件删除 Listview 项目

android - 加载纺车动画

javascript - 渲染部分文件 AngularJS

javascript - 带有 Base64 字符串的 Json 请求 URL

javascript - React-Native - 如何替换 React-Native 核心组件的功能

android - 使用 ListView-Adapter 预加载更多 View