![](/img/trans.png)
[英]Not able to display images in <img> tag in Reactjs when i have images in Array of objects
[英]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.