繁体   English   中英

我有一个包含图像和文档的对象数组,我想检查 mime_type 并选择要显示的第一个元素(React)<img> 标签

[英]I have a array of objects containing images and documents, I want to check the mime_type and pick the first element (React) to display in <img> tag

我有一个包含图像和文档的对象数组,我想检查 mime_type 是“images/jpeg”还是“image/png”,然后只显示标签中的第一个图像。 我正在使用反应。

我试过了,但我一直不确定

<img className={"img-fluid img-list"} 
   src={this.state.images.filter(img => (img.mime_type === 'image/jpeg' || img.mime_type === 'image/png') || {})[0].blob_url} 
   alt="" />


<img className={"img-fluid img-list"} 
   src={this.state.images.filter(img => (img.mime_type === 'image/jpeg' || img.mime_type === 'image/png'))[0].blob_url} 
   alt="" />

如果用 {} 检查我没有得到任何链接

任何帮助都非常感谢。

你在这里有一个错误:

this.state.images.filter(img => (img.mime_type === 'image/jpeg' || img.mime_type === 'image/png') || {})[0].blob_url

它应该是:

((this.state.images.filter(img => (img.mime_type === 'image/jpeg' || img.mime_type === 'image/png')) || [])[0] || {}).blob_url

如果您添加一些缩进,应该更清楚您的错误在哪里:

(
  (
    this.state.images.filter(img => (
      img.mime_type === 'image/jpeg' || img.mime_type === 'image/png'
    ))     // give me an array with only the images
    || []  // OR give me back an empty array if you cannot find any
  )[0]     // then give me the first element (image object) of the array
  || {}    // OR give me back an empty object if the array is empty
).blob_url // finally give me the `blobl_url` of the object

或者,您可以使用Array.prototype.find ,它将返回符合条件的第一个项目:

(this.state.images.find(img => (img.mime_type === 'image/jpeg' || img.mime_type === 'image/png')) || {}).blob_url

暂无
暂无

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

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