Kev*_*vvv 3 reactjs react-native react-hooks
我正在尝试使用功能组件中的钩子从 FlatList访问scrollToIndex()方法或scrollToItem()方法useRef。我希望能够flatListRef.current.ScrollToIndex()在我的组件中使用,类似于基于类的组件使用的方式this.flatListRef.ScrollToIndex():
const flatListRef = useRef(React.createRef)
<FlatList
data={items}
renderItem={({ item }) => <Item item={item} />}
keyExtractor={item => item.id.toString()}
contentContainerStyle={styles.card}
horizontal={true}
showsHorizontalScrollIndicator={false}
ref={flatListRef}
/>
Run Code Online (Sandbox Code Playgroud)
console.loggingflatListRef.current没有显示我正在寻找的上述方法。
您不需要使用 来创建 ref createRef,您只需使用useRef(). 另一个重要的事情是scrollToIndex正确使用。请参阅文档和下面的代码。
代码:
const CustomFlatList = () => {
const flatListRef = useRef(); // useRef
return (
<View>
<FlatList
data={items}
renderItem={({ item }) => <Text style={{width: 100}}> {item.id} </Text> }
keyExtractor={item => item.id.toString()}
contentContainerStyle={styles.card}
horizontal={true}
showsHorizontalScrollIndicator={false}
ref={flatListRef} // create ref
/>
<TouchableHighlight onPress={() => flatListRef.current.scrollToIndex({index: 4, animated: true })}>
<Text> ScrollToIndex </Text>
</TouchableHighlight>
</View>
)
}
Run Code Online (Sandbox Code Playgroud)
工作示例:
https://snack.expo.io/B1rfdbsuS
| 归档时间: |
|
| 查看次数: |
1486 次 |
| 最近记录: |