我有一个水平的平面列表,每个项目是width:300

<FlatList 
            onScroll={(e) => this.handleScroll(e)} 
            horizontal={true}
            data={this.state.data}
            renderItem...

试过这个:

handleScroll(event) {
    let index = Math.ceil(
      event.nativeEvent.contentOffset.x / 300
    );

比如:

handleScroll(event) {
  let contentOffset = event.nativeEvent.contentOffset;
  let index = Math.floor(contentOffset.x / 300);

but nothing is accurate I always get one index up or one index down.
What am I doing wrong and how to get correct current index in flat list?

For example I get to list item that is 8th in a list but I get index 9 or 10.
enter image description here

推荐答案

UPD.感谢@ch271828n指出onViewableItemsChanged不应更新

你可以使用FlatList onViewableItemsChangedprops 来获得你想要的东西.

class Test extends React.Component {
  onViewableItemsChanged = ({ viewableItems, changed }) => {
    console.log("Visible items are", viewableItems);
    console.log("Changed in this iteration", changed);
  }

  render () => {
    return (
      <FlatList
        onViewableItemsChanged={this.onViewableItemsChanged }
        viewabilityConfig={{
          itemVisiblePercentThreshold: 50
        }}
      />
    )
  }
}

任何你想要的设置都可以帮助你提高可视性.在代码示例50中,如果项目的可见率超过50%,则该项目被视为可见.

配置 struct 可以在here中找到

React-native相关问答推荐

React Native 无法下载模板

React Native 组件中两次使用map的问题

SignalR 与 React Native Expo:: 什么都没有发生

如何在 react-native 中刷新 Flatlist 数据?

无法执行 JS 调用:__fbBatchedBridge 未定义

ReactJS toLowerCase 不是一个函数

在 CircleCI 上 ReactNative 0.59.x build fails on CircleCI with exit value 137

React Native - 初始属性 Android

用hooks钩子react context上下文防止重新渲染

React Native - SectionList numColumns support

在 Docker 中使用 Fastlane 构建 iOS 应用

react-native createbottomtabnavigator 隐藏标签栏标签

如何在 React Native 中使用 index.js 而不是 (index.ios.js, index.android.js) 进行跨平台应用程序?

React-native:图像未显示在 android 设备中,但在模拟器中完美显示

horizontal水平 FlatList 前后的间距

React Native:如何将文件拆分为多个文件并导入它们?

更改导航标题背景 colored颜色

手动调用 React.PropTypes 验证 React native "^0.30.0"

将 colored颜色 变量导入我的样式

将 Picker 绑定到 React Native 中的 Picker.Item 列表