我正在尝试使用React Hooks和scrollToIndex方法滚动到扁平列表中的数据中间,但我无法引用它。我使用类似于ref={component => (this.list = component)}的类实现了这一点,但是我可以使用useRef来实现。
const refContainer = useRef(null);
useEffect(()=>{
if(refContainer){
refContainer.scrollToIndex({ animated: true, index: 0 });
}
},[status])
<FlatList
ref={()=>refContainer}
refreshing={loading}
onRefresh={() => console.log('refreshing')}
keyExtractor={(item, index) => item.date}
showsVerticalScrollIndicator={false}
style={{flex: 1,}}
data={kits}
onEndThreshold={0}
renderItem={({item, index}) => renderItem(item, index)}
/>显示错误: refContainer.scrollToINdex不是一个函数。
发布于 2020-03-06 22:35:08
要访问当前呈现的ref,您需要使用.current -因此,在您的示例中,使用refContainer.current
useEffect(()=>{
if(refContainer.current){
refContainer.current.scrollToIndex({ animated: true, index: 0 });
}
},[status])另外,像这样设置你的ref:
<FlatList ref={refContainer} ...(有关.current的更多信息,请参阅docs )
发布于 2021-04-13 15:35:25
步骤1:为平面列表创建ref,例如如下所示,
let myList = useRef();第2步:然后将ref添加到您flatlist组件,如下所示
<FlatList
data = {data}
ref={myList}
renderItem = {YourComponent}
initialScrollIndex={0}
horizontal = {true}
showsHorizontalScrollIndicator={false}
/>步骤3然后在任何按钮点击或类似下面的任何事件上滚动平面列表
myList.current.scrollToIndex({animated:true,index:0,viewPosition:0});谢谢!希望能有所帮助
发布于 2020-12-31 16:13:06
const flatListRef = useRef();
<FlatList
ref={flatListRef}
onContentSizeChange={() => flatListRef?.current?.scrollToEnd()} // scroll end
data={myChats}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item, index }) => <View/>}
/>https://stackoverflow.com/questions/60566164
复制相似问题