简体   繁体   English

在React中以编程方式检查img src

[英]Programmatic check for img src in React

I have a page with many customer logos on it in a table. 我在表格中的页面上有很多客户徽标。 One table cell tries to get the logo like this: 一个表格单元格试图获得如下徽标:

<TableCell className={classNames(classes.urlDealCell, classes.dealCell)}>
    {this.getLogo(deal.CompanyWebsite)}
</TableCell>

getLogo is: getLogo是:

getLogo = url => {
  const source = `https://logo.clearbit.com/${url}`;
  return <img src={source} width="30" />;
};

80% of the time, the logo comes back fine, and if there is no deal.CompanyWebsite , I can provide a default logo. 80%的时间,徽标恢复正常,如果没有deal.CompanyWebsite ,请deal.CompanyWebsite ,我可以提供默认徽标。 But I need to handle another edge case: 但是我需要处理另一个极端情况:

If the request to the img source fails with a URL like this: https://logo.clearbit.com/absoluteGarbage , can I somehow check this in React and fallback to the default logo? 如果对img源的请求失败,并出现如下URL: https : //logo.clearbit.com/absoluteGarbage ,我可以在React中以某种方式检查并回退到默认徽标吗?

Must I try a GET request to the src URL for each logo before trying to assign the src attribute of the img ? 尝试分配imgsrc属性之前,我是否必须尝试对每个徽标的src URL进行GET请求? If so, this would double the number of image requests, which would suck for larger page result sets. 如果是这样,这将使图像请求的数量增加一倍,这对于较大的页面结果集来说很糟糕。

  <img src={someurl} 
   onError={(e)=>{e.target.onerror = null; e.target.src="image_path_here"}}/>

When an image fails to load, onError gets called. 当图像加载失败时,将调用onError。 Use this function to do your logic 使用此功能来做你的逻辑

Use the onError attribute: 使用onError属性:

<img src="https://logo.clearbit.com/absoluteGarbage"
     onError={event => event.target.src=defaultUrl} />

JSFiddle: https://jsfiddle.net/g1wubsLm/1/ JSFiddle: https ://jsfiddle.net/g1wubsLm/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM