【问题标题】:How to go to a specific item(index) in FlatList如何转到 FlatList 中的特定项目(索引)
【发布时间】:2020-04-08 07:56:51
【问题描述】:

我看到了this,但我做不到。 我有一个名为 DAYS 的静态列表,并将其绑定到 FlatList,如下所示:

const DAYS = [
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
]

const App = () => {
  const onViewRef = useRef((viewableItems) => {
  })

  const viewConfigRef = useRef({ viewAreaCoveragePercentThreshold: 50 })

  return (
    <View style={styles.screen}>

      <Button title="Go To" onPress={() => { }} />
      <FlatList
        data={DAYS}
        horizontal={true}
        showsHorizontalScrollIndicator={false}
        keyExtractor={(item, index) => index.toString()}
        onViewableItemsChanged={onViewRef.current}
        viewabilityConfig={viewConfigRef.current}
        renderItem={({ item }) =>
          <View style={styles.textContainer}>
            <Text style={styles.text}>{item}</Text>
          </View>}
      />

    </View>
  )
}

运行后:

现在,当我点击按钮(GO TO)时,FlatList 应该如下:

(例如转到第 10 项,所选项目应居中)

【问题讨论】:

    标签: react-native react-native-flatlist


    【解决方案1】:

    通过阅读 scrollToIndexgetItemLayout 可能你可以做到:

    const DAYS = [
      1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
    ]
    
    const ITEM_WIDTH = 20 // size of you element
    
    const App = () => {
      const flatListRef = useRef(null)
    
      const onViewRef = useRef((viewableItems) => {
      })
    
      const viewConfigRef = useRef({ viewAreaCoveragePercentThreshold: 50 })
    
      return (
        <View style={styles.screen}>
    
          <Button title="Go To" onPress={() => {
            if (flatListRef.current) {
                flatListRef.current.scrollToIndex({index: 9}) // Scroll to day 10
            }
          }} />
          <FlatList
    
            ref={flatListRef} // add ref
            getItemLayout={(data, index) => (
              {length: ITEM_WIDTH, offset: ITEM_WIDTH * index, index}
            )}
    
            data={DAYS}
            horizontal={true}
            showsHorizontalScrollIndicator={false}
            keyExtractor={(item, index) => index.toString()}
            onViewableItemsChanged={onViewRef.current}
            viewabilityConfig={viewConfigRef.current}
            renderItem={({ item }) =>
              <View style={styles.textContainer}>
                <Text style={styles.text}>{item}</Text>
              </View>}
          />
    
        </View>
      )
    }
    

    【讨论】:

    • 谢谢。单击按钮后出现错误:scrollToIndex out of range: requested index undefined but maximum is 29
    • 我刚刚更新了答案。应该是 scrollToIndex({index: 9}) 而不是 scrollToIndex(9)
    • 点击按钮后,第10项将成为FlatList中的第一个元素,是否可以居中(如上图)? (uupload.ir/files/920j_primary.png)
    • 你应该使用偏移量。
    猜你喜欢
    • 2014-01-06
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 2010-10-09
    相关资源
    最近更新 更多