React backgroundImage referenced in JSON file path seem weird

前端 未结 1 1894
不知归路
不知归路 2021-01-25 11:11

My app is created with create-react-app,

Im iterating with .map through my JSON file where I store the local path to the image but I assume create-react-app changes the

相关标签:
1条回答
  • 2021-01-25 11:56

    Images need to be statically analysable so you need to require them. Please refer to this for more background info.

    So with your example above, instead of using a jsonfile create a people.js file instead like this with require statements for each image:

    // 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')
      }
    ]
    

    Then you can map over this info to produce the jsx and your images will render.

    const people = require('../path/to/people.js')
    
    renderPeopleList () {
      return people.map(p =>
        <div key={p.id} style={{ backgroundImage: `url(${p.picture})` />
      )
    }
    
    0 讨论(0)
提交回复
热议问题