想用 IntersectionObserver 创建延迟加载,但不能分配给类型 null (io.current)。当它在视口中时,它应该将 src 链接和 alt 文本分配给属性。 Snippet to codesandbox
import { FC, useRef, useEffect } from "react";
import { LazyLoaderProps } from '../../types/types';
export const LazyLoader: FC<LazyLoaderProps> = ({ src, alt }) => {
const ref = useRef(null);
const io = useRef(null);
useEffect(() => {
if (ref.current) {
io.current = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.intersectionRatio > 0.5) {
ref.current.src = src;
io.current.unobserve(ref.current);
}
});
},
{
threshold: [0, 0.5, 1]
}
);
io.current.observe(ref.current);
}
return () => {
io.current.unobserve(ref.current);
};
}, [ref]);
return <img ref={ref} srcalt={alt} />;
答案 0 :(得分:0)
试试这个:
import { FC, useRef, useEffect } from "react";
import { LazyLoaderProps } from '../../types/types';
export const LazyLoader: FC<LazyLoaderProps> = ({ src, alt }) => {
// Add explicit type, remove initial value since it should always be set by React during rendering
const ref = useRef<HTMLImageElement>();
useEffect(() => {
if (ref.current) {
const elem = ref.current;
// Using a local variable is enough for your use case
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.intersectionRatio > 0.5) {
elem.src = src;
observer.unobserve(elem);
}
});
},
{
threshold: [0, 0.5, 1]
}
);
observer.observe(elem);
return () => {
observer.unobserve(elem);
};
}
}, [ref]);
return <img ref={ref} srcalt={alt} />;
};