如何在React JS中检查损坏的图像

nyh*_*r77 7 javascript error-handling state reactjs

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

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

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

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

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;
Run Code Online (Sandbox Code Playgroud)

我以这种方式显示信息:

<div className={imageContainerClassName} style={customBackgroundStyles}>
      {newsImage ? <img className="img-responsive" src={newsImage} alt={headline}/> : <img className="img-responsive" src={defaultImage} alt={headline}/>}
</div>
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能检查损坏的图像?我想这是所有需要的相关数据,请告诉我是否应该展示其他内容.谢谢!

elt*_*ami 28

调用的图像有一个本机事件,onerror如果无法加载图像,则可以执行操作.

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

//in your component
addDefaultSrc(ev){
  ev.target.src = 'some default image url'
}
Run Code Online (Sandbox Code Playgroud)