小编典典

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

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;

我以这种方式显示信息:

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

为了检查是否有损坏的图像该怎么办?我认为这是所需的所有相关数据,请告诉我是否还有其他内容。谢谢!


阅读 263

收藏
2020-07-22

共1个答案

小编典典

对于图像onerror,有一个本机事件,如果无法加载图像,则可以执行操作。

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

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