JSON文件路径中引用的React backgroundImage看起来很奇怪

时间:2017-06-23 17:18:38

标签: reactjs create-react-app

我的应用是使用create-react-app创建的,

我通过我的JSON文件迭代.map,我存储了图像的本地路径,但我认为create-react-app以某种方式更改路径,我不明白如何。

const list = this.state.people.map((d, i) => { return <li
    key={i}
    className="content"
    style={{ backgroundImage: `url(${d.Picture})` }}
    >

上面是我的开始li标签,我从下面的JSON文件中循环出数据: “亚当”中的图片效果很好并显示在页面上,但这不是图片的存储位置。我在chrome dev工具中找到了这条路径,所以我只是复制粘贴。

以下“Bob”中的示例是img的实际路径(来自root) 我希望能够将所有图像放在images文件夹中,并将正确的路径存储在JSON文件中

{
  "Name": "Adam",
  "Born": 1971,
  "Picture": "/static/media/elonmusk.3489bce1.jpg"
},

{
  "Name": "Bob",
  "Born": 1999,
  "Picture": "/src/css/images/elonmusk.jpg"
},

enter image description here

上面是我的文件夹结构,App.js是我渲染数据的地方,persons.json是我存储文件路径的地方,而images是我有图像的文件夹

1 个答案:

答案 0 :(得分:0)

图像需要是静态可分析的,因此您需要require它们。有关background信息的详细信息,请参阅此处。

因此,使用上面的示例,而不是使用json文件,而不是使用每个图像的require语句创建people.js文件:

// file: people.js

const people = [
  {
    id: 0,
    name: 'Adam',
    born: 1971,
    picture: require('../path/to/image.jpg')
  },
  {
    id: 1,
    name: 'Bob',
    born: 1999,
    picture: require('../path/to/image2.jpg')
  }
]

然后,您可以映射此信息以生成jsx,您的图像将呈现。

const people = require('../path/to/people.js')

renderPeopleList () {
  return people.map(p =>
    <div key={p.id} style={{ backgroundImage: `url(${p.picture})` />
  )
}