useRef元素的高度大于零时的事件

问题描述

我的照片缩略图列表很大,加载列表时,我应该能够将其中一个缩略图滚动到视图中。

使用map功能填充照片,并且缩略图的容器div之一将被赋予ref

我尝试过useEffect:

useEffect(() => {
    if (scrollRef.current && scrollRef.current instanceof HTMLdivelement) {
        scrollRef.current.scrollIntoView({
            behavior: 'auto',block: 'center',inline: 'center',});
    }
},[scrollRef.current]);

问题是refref.current不能用作useEffect的依赖项列表。我得到警告:

React Hook useEffect具有不必要的依赖性: 'scrollRef.current'。排除它或删除依赖项数组。 像'scrollRef.current'这样的可变值不是有效的依赖项 因为对其进行突变不会重新渲染组件

ref.current更改时,如何触发useEffect或其他功能?通过更改,我的意思是专门指其clientHeight值更改。因为最初它是零,所以scrollIntoView尚不可用。

解决方法

使用callback ref

function Example() {
    const [divRef,setDivRef] = useState(null);

    useEffect(() => {
        if (divRef && divRef.clientHeight > 0) {
            div.scrollIntoView({
                behavior: 'auto',block: 'center',inline: 'center',});
        }
    },[divRef]);

    return <div ref={setDivRef} />;
}