2017-03-17 40 views
-1

我想使用JSON檢索我的圖像及其文件位置。我的程序看起來像下面的代碼。如何從JSON中將圖像檢索到React中?

我試過{photos.Lillian.portfolioImage}JSON.stringify(photos.Annalise.portofolio但是,它們都不能顯示圖像。我已經完成了console.log();,並檢查數據是否可以讀取,但確實出現,但圖像不會出現。我已經檢查了源地址,它在我在這裏添加它的時候有效<img src="./img/TheGuardian/Lillian.png">

我的錯誤是什麼?我需要重新格式化從JSON調用的對象嗎?我已經看到一個可以使用解析和獲取,但是,這是用於API和據我所知,這不是?

這裏是我的JSON:

{ 
    "Lillian" : { 
    "type": "The Guardian", 
    "portfolioImage": "./img/TheGuardian/Lillian.png" 
    }, 
    "Annalise" : { 
    "type": "TheGuardian", 
    "portfolioImage": "./img/TheGuardian/Annalise.png" 
    }, 
    "Raven" : { 
    "type": "DCComics", 
    "portfolioImage": "./img/TheGuardian/Raven.png" 
    } 
} 

這裏是我的HTML:

import React, { Component } from 'react'; 
import logo from './logo.svg'; 
import photos from './images.json'; 
import './App.css'; 

class App extends Component { 
    render() { 
    console.log(JSON.stringify(photos.Annalise.portfolioImage)); 

    return (
     <div className="App"> 
     <div className="App-header"> 
      <img src={logo} className="App-logo" alt="logo" /> 
      <h2>beeccy´s portfolio.</h2> 
     </div> 
     <p className="App-intro"> 
      This was a test to present images from my portfolio. 
     </p> 
     <img src={photos.Lillian.portfolioImage} alt="Lillian" /> 
     <img src={photos.Raven.portfolioImage} alt="Raven" /> 
     <img src="JSON.stringify(photos.Annalise.portfolioImage)" alt="Annalise" /> 
     </div> 
    ); 
    } 
} 

export default App; 
+1

那麼如何創建一個標籤並將路由放入src屬性呢? – Borjante

回答

0
const obj = 

    { 
      "Lillian" : { "type": "The Guardian", "portfolioImage":   "./img/TheGuardian/Lillian.png" }, 

      "Annalise" : { "type": "TheGuardian", "portfolioImage": "./img/TheGuardian/Annalise.png" }, 

      "Raven" : { "type": "DCComics", "portfolioImage": "./img/TheGuardian/Raven.png" } 
    }; 

    let images = []; 

    for(let item in obj){ 
     images.push(item.portfolioImage); 
    } 

這樣做,你可以檢索對象的對象圖像轉換成圖像陣列

1

像在HTML中,你想設置一個img元素的src屬性的源代碼e到圖像。以下示例還顯示瞭如何遍歷JSON並一次顯示所有圖像。

const JSON = { 
    Lillian: { 
    type: 'The Guardian', 
    portfolioImage: './img/TheGuardian/Lillian.png' 
    }, 
    Annalise: { 
    type: 'TheGuardian', 
    portfolioImage: './img/TheGuardian/Annalise.png' 
    }, 
    Raven: { type: 'DCComics', portfolioImage: './img/TheGuardian/Raven.png' } 
}; 

class Example extends React.Component { 
    render() { 
    return (
     <div> 
     {Object.keys(JSON).map(key => (
      <div> 
      {JSON[key].type} 
      <img src={JSON[key].portfolioImage} key={key} /> 
      </div> 
     ))} 
     </div> 
    ); 
    } 
} 

ReactDOM.render(<Example />, document.getElementById('root')); 
+0

這工作。你怎麼能打印這個類型,假設它是一個字符串? – santafebound

+0

只需將它包裝在花括號中,如{JSON [key] .type}'。還更新了我的答案。 –

相關問題