在typescript钩子中懒惰地加载元素不起作用



我已经实现了一个延迟加载挂钩,但由于某种原因,carousel组件根本没有加载。我从这里得到了:https://betterprogramming.pub/lazy-loading-in-next-js-simplified-435681afb18a

这是我的孩子,我想在它出现时渲染:

import { useRef } from "react";
import Carousel from "../components/carousel";
import useOnScreen from "../hooks/useOnScreen";
// home page
function HomePage() {
const carouselRef = useRef();
const carouselRefValue = useOnScreen(carouselRef);
return (
<div className="snap-y">
{/* 1 */}
<div className="flex justify-center items-start relative min-h-[calc(100vh_-_5rem)] bg-black snap-start ">
{/* Cone */}
<div className="absolute w-full max-w-full overflow-hidden min-w-fit cone animate-wiggle"></div>

<div className="grid justify-center grid-cols-4 max-w-7xl">
//Content
</div>

{/* 2 */}
<div className="z-20 pb-4 bg-black snap-start" ref={carouselRef.current}>
{carouselRefValue && <Carousel />}
</div>

{/* 3 */}
<div className="flex items-start justify-center py-32 min-h-fit bg-slate-50 snap-start">
//More content
</div>
);
}
export default HomePage;

useOnScreen挂钩:

import { useState, useEffect } from "react";
const useOnScreen = (ref: any) => {
const [isIntersecting, setIntersecting] = useState(false);
useEffect(() => {
const observer = new IntersectionObserver(([entry]) => setIntersecting(entry.isIntersecting));
if (ref.current) {
observer.observe(ref.current);
}
}, []);
return isIntersecting;
};
export default useOnScreen;

编辑:需要添加const carouselRef = useRef() as React.MutableRefObject<HTMLInputElement>;,并与@synts的答案配对。

这是不正确的:

<div className="z-20 pb-4 bg-black snap-start" ref={carouselRef.current}></div>

应该是:

<div className="z-20 pb-4 bg-black snap-start" ref={carouselRef}></div>

最新更新