import React, { Component } from "react";
class uploader extends Component {
constructor(props) {
super(props);
this.state = {};
}
onImageChange = event => {
if (event.target.files && event.target.files[0]) {
let reader = new FileReader();
reader.onload = e => {
this.setState({ images: e.target.result });
};
reader.readAsDataURL(event.target.files[0]);
}
};
render() {
return (
<div class="preview">
<img id="target" src={this.state.image} />
</div>
<div>
<input id="imageupload" type="file" onChange={this.onImageChange} />
</div>
);
}
}
export default uploader;
我正在尝试显示图像预览,显示用户选择了什么,一旦用户选择了第二幅图像,则先前的图像将替换为新的图像,但是我想在预览部分显示这两个图像。我们该怎么做?预先感谢
答案 0 :(得分:0)
当前和先前的图像预览
选择第二张图片后,两者都会显示(当前和上一张)。
import React from "react";
const dummy = "https://static.thenounproject.com/png/625182-200.png";
class MultipleImageUpload extends React.Component {
state = { current: null, old: [] };
uploadImage = e => {
const { current, old } = this.state;
this.setState(
{
current: URL.createObjectURL(e.target.files[0])
},
() => {
this.setState({ old: [...old, current] });
}
);
this.setState({ current: URL.createObjectURL(e.target.files[0]) });
};
render() {
console.log(this.state);
const { old, current } = this.state;
return (
<div className="App">
<div>
<h3>Current</h3>
<img
src={current ? current : dummy}
alt="custom-pic"
style={{ height: 100, width: 100 }}
/>
</div>
<hr />
{old
? old.map((o, i) => (
<img
src={o ? o : dummy}
key={i.toString()}
alt="preview"
style={{ height: 100, width: 100 }}
/>
))
: ""}
<input type="file" onChange={this.uploadImage} />
</div>
);
}
}
export default MultipleImageUpload;