在 React 中的 div 组件上设置背景图像时,如何检测断开的链接?


<div className="image" style={{ backgroundImage: `url(${entity.image_url})`}} />}

我通过将 url 作为内联样式属性传递来设置背景图像。但是,有时图像链接会断开。我熟悉标签的错误事件。但是,我不熟悉在设置背景图像时如何检测断开的链接。我正在考虑尝试在隐藏中加载图像并使用 onerror 属性,但这需要我加载图像两次,这是浪费。有什么更好的方法呢?

老派的风格是预加载所有图像。 预加载图像

现在,您将图像放在js对象中,并且不会再次或两次加载图像。通过这种方式,您还可以检查其是否损坏 检测损坏的图像.当然,如果您使用聪明的 AJAX 生活方式,您还可以检测和替换损坏的图像。

为什么不写一些JS并测试entity.image_url。 如果你没有找回一个对象,它将显示为未定义或空。 为两者提供一个if语句来涵盖可能性。

if (entity === undefined || entity === null) {
//write an error message
} else {
//drop a dynamic template literal into your html
//you can either appendChild() or build a string and user innerHTML
}

这就是我在 React 中做到这一点的方式:

import noImage from <local_image_path>;
{(entity && entity.image) ?
<div style={{backgroundImage: `url(${entity.image}), url(${noImage})`}}/> :
<div style={{backgroundImage: `url(${noImage})`}}/>
}

这处理了两种情况。情况1:图片链接断开。如果 entity.image url 上有 404,则加载 noImage。情况 2:实体图像未定义,未加载图像。

最新更新