为什么不能在img上运行React onLoad



我想在加载图像时执行loadImg1变量为false;重新渲染过多。React限制渲染次数,以防止出现无限循环。

const [loadImg1, setLoadImg1] = useState(true);
{
Array.isArray(data) &&
data.map((value, index) => (
<img
key={index}
className={cls(count == index ? css.avatar : css.noFoto)}
src={value.photoUrl}
loading={`${index === 0 ? "eager" : "lazy"}`}
onLoad={setLoadImg1(false)}
/>
));
}

在react中,您必须为类似onLoad={()=>setLoadImg1(false)}的事件提供函数定义。根据您当前的代码onLoad={setLoadImg1(false)},它将在组件渲染时执行setLoadImg1(false),而不是在加载图像之后执行。当您的图像实际加载时,onLoad事件将找不到任何要执行的函数。

const [loadImg1, setLoadImg1] = useState(true);
{
Array.isArray(data) &&
data.map((value, index) => (
<img
key={index}
className={cls(count == index ? css.avatar : css.noFoto)}
src={value.photoUrl}
loading={`${index === 0 ? "eager" : "lazy"}`}
onLoad={()=>setLoadImg1(false)}
/>
));
}
正如人们早些时候在评论中所说的那样。使用setLoadImg1(false)与使用() => setLoadImg1(false)有很大区别。

到底有什么区别

当您使用类似setLoadImg1(false)的东西并将其作为道具传递给您的某个组件时,无论是否发生onLoad事件,React都会在第一页加载期间自动运行该程序,另一方面,当onLoad事件将要发生时,它将被再执行一次(这是没有意义的,因为它在它之前刚刚执行了一次,并且loadImg1已经被设置为false(,所以我们这里至少有两个重发器。

但是,当您使用函数定义(如() => setLoadImg1(false)(时,它只会在onLoad事件触发时触发。

所以最终的输出应该是这样的:

const [loadImg1, setLoadImg1] = useState(true);
{
Array.isArray(data) &&
data.map((value, index) => (
<img
key={index}
className={cls(count == index ? css.avatar : css.noFoto)}
src={value.photoUrl}
loading={`${index === 0 ? "eager" : "lazy"}`}
onLoad={()=>setLoadImg1(false)}
/>
));
}

最新更新