如何在 React JS 中检查损坏的图像 [英] How to check for broken images in React JS

查看:21
本文介绍了如何在 React JS 中检查损坏的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个模块,它从 json 中获取文章数据,并在文章文本上显示一个大图像,正如他们所说的那样,是一个英雄模块.

我已经获取了数据并进行了设置,因此如果有图像,它将显示该图像,如果数据中没有图像,它将显示默认图像.问题是此方法不会替换损坏的链接以显示默认图像.

我对反应和使用状态仍然是新手......问题是,我应该使用状态来检查断开的链接,我该怎么做?

这就是我如何在模块中将数据作为道具获取:

const { newsItemData: {标题 = '',署名 = [],发布日期:发布日期 = '',更新日期:更新日期 = '',链接:新闻链接 = '',内容分类:类别 = '',摘要:previewText = '',抽象图像:{ 文件名:新闻图像 = '' } = {},表面:{ 特征:{ 类型:特征类型 = '' } = {} } = {},} = {},宽视野,显示药丸,defaultImage } = this.props;

我以这种方式显示信息:

{新闻图片?<img className="img-responsive" src={newsImage} alt={headline}/>: <img className="img-responsive" src={defaultImage} alt={headline}/>}

我应该怎么做才能检查损坏的图像?我认为这是所需的所有相关数据,让我知道是否应该显示其他内容.谢谢!

解决方案

有一个名为 onerror 的图像原生事件,可以在图像无法加载时执行操作.

<img onError={this.addDefaultSrc} className="img-responsive" src={newsImage} alt={headline}/>//在你的组件中addDefaultSrc(ev){ev.target.src = '一些默认图片网址'}

I'm writing a module that takes article data from json and shows a large image over the article text, a hero module as they say.

I've got the data and have set it up so if there is an image, it will show that image and if there is no image in the data, it will show a default image. Problem is that this method doesn't replace broken links to show the default image.

I'm still new to react and using state ... question is, should I be using state to check for the broken link and how do I do it?

This is how I get the data in as props in the module:

const { newsItemData: {
          headline = '',
          bylines = [],
          publishedDate: publishDate = '',
          updatedDate: updatedDate = '',
          link: newsLink = '',
          contentClassification: category = '',
          abstract: previewText = '',
          abstractimage: { filename: newsImage = '' } = {},
          surfaceable: { feature: { type: featureType = '' } = {} } = {},
        } = {},
        wideView,
        showPill,
        defaultImage } = this.props;

I display the info in this way:

<div className={imageContainerClassName} style={customBackgroundStyles}>
      {newsImage ? <img className="img-responsive" src={newsImage} alt={headline}/> : <img className="img-responsive" src={defaultImage} alt={headline}/>}
</div>

What should I do in order to also check for broken images? I think this is all the pertinent data needed, let me know if I should show anything else. Thanks!

解决方案

There is a native event for images called onerror that lets perform an action if the image cannot be loaded.

<img onError={this.addDefaultSrc} className="img-responsive" src={newsImage} alt={headline}/>

//in your component
addDefaultSrc(ev){
  ev.target.src = 'some default image url'
}

这篇关于如何在 React JS 中检查损坏的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆