简体   繁体   中英

Best practice to use image in react

Just curious how do you use picture in react? I use webpack so I assume it would be like this

import Picture from '../assets/images/mypic.jpeg'

render(){
   <div>
      <Picture />
   </div>
}

but isn't that tedious to import every single images u want to use?

You use img tags just like in HTML:

import myPicture from '../assets/images/mypic.jpeg'


render() {
  <div>
    <img src={myPicture} alt="My Picture" />
  </div>
}

Stole function from here

Have not tested it myself, but it sounds similar to what you're looking for.

const importAll = (r) => r.keys().map(r);

const images = importAll(require.context('../assets/images/', false, /\.(png|jpe?g|svg)$/));


render() {
  return (
    <div>
      {images.map((pic, i) =>
        <img src={pic} alt={`picture-${i}`} />
      }
    </div>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM