2017-08-14 19 views
0

我目前正在學習和練習React。如何創建可以渲染Img或Video的React組件,具體取決於它接收的API數據

我正在嘗試實現一個反應網絡應用程序,該應用程序允許您根據您選擇的日期顯示並滾動瀏覽Nasa當天的圖片。這裏是api:api.nasa.gov/

該項目很簡單但是。有時api返回的網址會導致img,有時會導致YouTube視頻。例如:

https://apod.nasa.gov/apod/image/1708/PerseidsTurkey_Tezel_960.jpg

https://www.youtube.com/embed/Zy9jIikX62o?rel=0

我已成功地顯示使用iframe這兩種情況。我知道這是不理想的imgs,因爲我不能用css正確格式化,它看起來不好用滾動條,大小等..但不會顯示視頻..

這是什麼反應組件看起來像(使用自舉)

detail.js

import React, { Component } from 'react'; 

export default class Detail extends Component { 
    render() { 
    return (
     <div className="video-detail col-md-12"> 
     <div className="embed-responsive embed-responsive-16by9"> 
      <iframe className="embed-responsive-item" src={this.props.url}> 
      </iframe>  
     </div> 
     </div> 
    ); 
    } 
} 

我想圖像還響應地顯示,居中和原始的寬高比,而且仍然有視頻顯示正確,因爲它們。

我已經嘗試在下放置額外的<img>,但這只是渲染圖像兩次。有沒有辦法根據條件呈現<img>或?

我想知道下一步應該嘗試什麼策略?有任何想法嗎?

謝謝!

回答

0

你應該使用conditional rendering

const isImage = this.props.url.split().pop() === 'jpg'; 
return (
    { 
    isImage ? <img src={this.props.url} /> 
    : <iframe className="embed-responsive-item" src={this.props.url}> 
     </iframe> 
    } 
) 

const isImage = this.props.url.split().pop() === 'jpg'; 
return (
    { 
    isImage && <img src={this.props.url} /> 
    } 
    { 
    !isImage && <iframe className="embed-responsive-item" src={this.props.url}> 
     </iframe> 
    } 
) 
+0

大它的工作完美!我剛剛添加了一個修改「。」:\t const isImage = this.props.url.split('。')。pop()==='jpg'; –

+0

我以爲分裂使用。作爲默認分隔符,tnx你教了我一些東西;) –

相關問題