【发布时间】:2018-07-19 10:52:05
【问题描述】:
我正在尝试处理多个图像上传并在提交表单之前将它们显示给用户。
我无法显示所有上传的图片。无论上传多少张图片,都只会显示最后一张。
我在 StackOverflow 上阅读了很多关于 javascript 闭包的答案,但它们似乎只处理被保留的循环中的索引值。
我不知道如何让它显示所有上传的图像。
class ImageDisplayBlock extends Component {
render(){
var counter = 0;
let pictureList = this.props.pictures.map(function(i){
return <img src={i} style={this.props.styles} key={counter++} alt="image" />
}.bind(this));
return(<div>{pictureList}</div>);
}
}
class ImageUploadBlock extends Component{
constructor(props){
super(props);
this.state ={
pictures : [],
imgRes : null
};
this.handleClick = this.handleClick.bind(this);
this.handleImage = this.handleImage.bind(this);
this.handleImageHelper = this.handleImageHelper.bind(this);
}
handleClick(event){
event.preventDefault();
this.props.setDisplay();
}
handleImageHelper(data){
this.setState(({pictures})=> ({ pictures:pictures.concat(data)}));
this.setState({
//pictures : this.state.pictures.concat(data),
imgRes : true //flag to allow component to be displayed
});
}
handleImage(event){
var f = event.target.files;
for(var key in f){
if(!f.hasOwnProperty(key)){ continue; }
var fReader = new FileReader();
fReader.readAsDataURL(f[key]);
fReader.onloadend = function(){
this.handleImageHelper(fReader.result);
}.bind(this);
}
}
render(){
return(
<div>
{this.state.imgRes && <ImageDisplayBlock
pictures={this.state.pictures}
styles={{"maxWidth":"100px"}}
/>}
<label htmlFor="file">select an image</label>
<br />
<input
onChange={this.handleImage}
type="file" multiple
id="file"
/>
<a onClick={this.handleClick} href="">close</a>
</div>
);
}
}
任何帮助都将不胜感激,因为我已经花了几个小时试图解决这个错误。
提前致谢
【问题讨论】:
标签: javascript reactjs closures