如何从JSON检索图像到React?

时间:2017-03-17 10:03:13

标签: html json reactjs

我想使用JSON来检索我的图像及其文件位置。我的程序看起来像下面的代码。

我尝试使用{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;

2 个答案:

答案 0 :(得分:2)

与HTML一样,您希望将src元素的img属性设置为图像的源。以下示例还说明了如何循环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'));

答案 1 :(得分: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);
    }

通过这样做,您可以将对象对象中的图像检索到图像数组