Как go указывать c элемент (индекс) в FlatList - PullRequest
1 голос
/ 08 апреля 2020

Я видел это , но я не мог сделать. У меня есть список stati c с именем 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>
  )
}

после запуска:

enter image description here

Теперь, когда я нажимаю на кнопку (GO TO), FlatList должен выглядеть следующим образом:

(например, go для элемента 10, выбранный элемент должен быть в центре)

enter image description here

1 Ответ

1 голос
/ 08 апреля 2020

Читая scrollToIndex и getItemLayout , вероятно, вы можете сделать:

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