我试图在使用 ReactJS 和FileReader()
API上传到服务器之前在浏览器中预览多个图像。但是,我遇到的问题是每次选择一些图像进行预览时,只显示最后一张图像。
我的代码如下所示:
class App extends Component {
constructor(props){
super(props);
this.state = {
id: "upload-photo",
imageURI: null
}
}
buildImgTag(){
let imgTag = null;
if (this.state.imageURI !== null) {
imgTag = (
<div className="photo-container">
<img className="photo-uploaded" src={this.state.imageURI} alt="Photo uploaded"/>
</div>
);
return imgTag;
}
}
readURI(e){
if (e.target.files) {
let filesAmount = e.target.files.length;
let i;
for (i = 0; i < filesAmount; i++) {
let reader = new FileReader();
reader.onload = function(ev) {
this.setState (
{
imageURI: ev.target.result
}
)
}.bind(this);
reader.readAsDataURL(e.target.files[i]);
}
}
}
handleChange(e){
this.readURI(e);
if (this.props.onChange !== undefined) {
this.props.onChange(e);
}
}
render() {
const imgTag = this.buildImgTag();
return (
<div className="container">
<div className="row justify-content-center">
<div className="col-md-6">
<div className="card">
<div className="card-header" style={{backgroundColor: 'rgb(232, 245, 253)', borderTopLeftRadius: '4px', borderTopRightRadius: '4px', display: 'flex', maxHeight: '50vh', minHeight: '25vh', overflow: 'hidden'}}>
<div className="avatar">
<img src="http://laratweet.local:8080/images/avatar-default.png" alt="User Avatar" className="user-avatar"/>
</div>
<div id="textEditor">
<form method="post" action="" encType="multipart/form-data">
<textarea name="" id="richTextArea" placeholder="What's happening?"></textarea>
{imgTag}
<div id="theRibbon">
<div>
<input
id={this.state.id}
type="file"
name=""
accept="image/gif,image/jpeg,image/jpg,image/png,video/mp4,video/x-m4v"
title="Add photos or video"
onChange={this.handleChange.bind(this)}
multiple
/>
<label htmlFor={this.state.id}>
<figure>
<svg xmlns="http://www.w3.org/2000/svg" width="30" height="27"
viewBox="0 0 20 17" className="upload-icon">
<path
d="M10 0l-5.2 4.9h3.3v5.1h3.8v-5.1h3.3l-5.2-4.9zm9.3 11.5l-3.2-2.1h-2l3.4 2.6h-3.5c-.1 0-.2.1-.2.1l-.8 2.3h-6l-.8-2.2c-.1-.1-.1-.2-.2-.2h-3.6l3.4-2.6h-2l-3.2 2.1c-.4.3-.7 1-.6 1.5l.6 3.1c.1.5.7.9 1.2.9h16.3c.6 0 1.1-.4 1.3-.9l.6-3.1c.1-.5-.2-1.2-.7-1.5z"/>
</svg>
</figure>
<span className="tooltiptext">Add photos or video</span>
</label>
</div>
<button type="submit" className="tweet">Tweet</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
我希望在浏览器中显示/预览所有选定的图像,但只预览最后一个图像。我究竟做错了什么?