Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

javascript - How to check for broken images in React JS

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...