[英]Type 'IntersectionObserver' is not assignable to type 'null'. TS2322 [React, intersectionObserver]
Want to create lazy loading with IntersectionObserver, but cannot assign to type null (io.current).想用 IntersectionObserver 创建延迟加载,但不能分配给类型 null (io.current)。 it should assign src link and alt text to attribute when it is in viewport.
当它在视口中时,它应该将 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} />;
Try this:试试这个:
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} />;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.