Flatlist scrollToIndex with Hooks useRef [英] Flatlist scrollToIndex with Hooks useRef

查看:83
本文介绍了Flatlist scrollToIndex with Hooks useRef的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 React Hooks 和方法 scrollToIndex 滚动到我在 flatlist 中的数据的中间,但我无法引用它.我使用类似 ref={component => (this.list = component)} 的类实现了这一点,但我可以通过 useRef 实现.

Im trying to scroll to the middle of my data in flatlist using React Hooks and the method scrollToIndex but i cant make reference to it. I achieved that with class using something like ref={component => (this.list = component)} but i can reached with 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 不是函数.

shows me the error: refContainer.scrollToINdex is not a function.

推荐答案

要访问当前渲染的 ref,您需要使用 .current - 所以在您的情况下,使用 refContainer.current:

To access the ref of the current render, you need to use .current - so in your case, use refContainer.current:

useEffect(()=>{   
        if(refContainer.current){
            refContainer.current.scrollToIndex({ animated: true, index: 0 });

        }    
    },[status])

另外,像这样设置你的引用:

Also, set up your ref like this:

<FlatList ref={refContainer} ...

(有关 .current 的更多信息,请参阅 docs/code>)

(See the docs for more info on .current)

这篇关于Flatlist scrollToIndex with Hooks useRef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆