【问题标题】:Is there a way to lazyload the image in CardMedia component in material ui?有没有办法延迟加载材料 ui 中 CardMedia 组件中的图像?
【发布时间】:2022-12-07 11:22:29
【问题描述】:
我正在尝试延迟加载 CardMedia 组件中的图像。是否有我可以使用的属性或任何其他方式将图像的延迟加载合并到组件中。
<CardMedia
key={cardIndex}
component="img"
style={{objectFit: 'contain', height: props.height}}
image={(cardItem)}
/>
【问题讨论】:
标签:
css
reactjs
image
material-ui
lazy-loading
【解决方案1】:
要在 CardMedia 组件中延迟加载图像,您可以使用 lazy 属性。以下是如何使用它的示例:
<CardMedia
key={cardIndex}
component="img"
style={{objectFit: 'contain', height: props.height}}
image={cardItem}
lazy
/>
lazy 属性告诉组件只加载位于视口中的图像,这可以提高应用程序的性能。
或者,您可以使用 IntersectionObserver API 在您的组件中实现延迟加载。这是您如何做到这一点的示例:
import React, { useRef, useEffect } from 'react';
import CardMedia from '@material-ui/core/CardMedia';
const LazyCardMedia = (props) => {
const imgRef = useRef(null);
useEffect(() => {
// Create an IntersectionObserver instance
const observer = new IntersectionObserver((entries) => {
// Check if the image is intersecting with the viewport
if (entries[0].isIntersecting) {
// If it is, set the src attribute of the img element
// to load the image
imgRef.current.src = props.image;
}
});
// Start observing the img element
observer.observe(imgRef.current);
}, []);
return (
<CardMedia
component="img"
style={{objectFit: 'contain', height: props.height}}
ref={imgRef}
/>
);
}
在此示例中,LazyCardMedia 组件使用 useRef 和 useEffect 挂钩创建一个观察 img 元素的 IntersectionObserver 实例。当图像在视口中时,设置 img 元素的 src 属性以加载图像。