如何检查React JS中的破碎图像 [英] How to check for broken images in React JS
问题描述
我有获取数据并进行设置,如果有图像,它将显示图像,如果数据中没有图像,它将显示默认图像。
问题是这个方法不会取代破坏的链接来显示默认的图像。
我还没有反应和使用状态...问题是,我应该使用状态检查断开的链接,我该怎么做?
这是我如何将数据作为模块中的道具获取: / p>
const {newsItemData:{
headline ='',
bylines = [],
发布日期: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-responsivesrc = {newsImage} alt = {headline} /> :< img className =img-responsivesrc = {defaultImage} alt = {headline} />}
< / div>
为了检查图像是否损坏,我该怎么办?
我认为这是所有相关数据,让我知道如果我应该显示任何其他的。
谢谢!
有一个本地事件,称为 onerror
如果图像无法加载,可以执行一个操作。
< img onError = {this.addDefaultSrc} className =img-responsivesrc = {newsImage} alt = {headline} />
//在你的组件
addDefaultSrc(ev){
ev.target.src ='一些默认的图像url'
}
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屋!