简体   繁体   中英

select multiple images using <input type=“file” />, update the state to store the image URLs, dynamically add <img /> tags to display them in reactjs

this.state = {
  imageURL: []
};

fileSelectHandler = (event) => {
  this.setState({
    imageURL: [???]
  });
}

<input type="file" multiple onChange={fileSelectHandler} />
<img src={imageURL[0]} />

Here I need to dynamically add multiple img tags according to the number of images selected. Please help!

On File change you can try the sample code here

fileSelectHandler = (e) => {
    Array.from(e.target.files).forEach(file => {
      const reader = new FileReader();
      reader.onload = (e) => {
      this.setState({
        images: this.state.images.concat(e.target.result),
      });
    };
    reader.readAsDataURL(file);
  })
}

A demo is here https://codesandbox.io/s/qxxzz1q11j

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