我的反应原生应用程序中有这个类别过滤器组件。第一次加载此组件时,它不会滚动到给定的索引项(即 3)。我检查了一下,函数scrollToIndex
正在调用。但是在加载屏幕后重新渲染组件时它正在工作。
为什么在第一次加载屏幕时它不向下滚动?
import React, { useCallback, useRef } from 'react'
import { StyleSheet, TouchableOpacity, FlatList, View } from 'react-native'
import { Badge, Text } from 'native-base'
import { connect } from 'react-redux'
import * as categoryActions from '../../Redux/Actions/categoryActions'
import { useFocusEffect } from '@react-navigation/native'
const CategoryFilter = (props) => {
const flatlistRef = useRef()
const handleSetSelectedCategoryId = (categoryId) => {
props.setSelectedCategoryId(categoryId)
}
const getItemLayout = (data, index) => ({
length: 50,
offset: 50 * index,
index,
})
const scrollToIndex = () => {
console.log('scroll to index called !')
let index = 3
flatlistRef.current.scrollToIndex({ animated: true, index: index })
}
useFocusEffect(
useCallback(() => {
scrollToIndex()
}, [])
)
const renderItem = ({ item, index }) => {
return (
<TouchableOpacity
key={item._id}
onPress={() => {
handleSetSelectedCategoryId(item._id)
}}
>
<Badge
style={[
styles.center,
{ margin: 5, flexDirection: 'row' },
item._id == props.selectedCategoryId
? styles.active
: styles.inactive,
]}
>
<Text style={{ color: 'white' }}>{item.name}</Text>
</Badge>
</TouchableOpacity>
)
}
return (
<View>
<FlatList
data={props.categories}
renderItem={renderItem}
keyExtractor={(item) => item._id}
horizontal={true}
ref={flatlistRef}
getItemLayout={getItemLayout}
/>
</View>
)
}
....