我在React中有一个组件负责图像预览。我也可以选择删除图像。我注意到,如果我已上传图像,然后将其删除,则想再次上传它就无法预览。为什么会这样呢? 这是我的组件:
class MediaPlaceholder extends Component {
constructor(props) {
super(props)
this.state = {
fileUrl: null
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event) {
this.setState({
fileUrl: URL.createObjectURL(event.target.files[0])
})
}
removeImage() {
this.setState((prevState) => {
URL.revokeObjectURL(prevState.fileUrl);
return {fileUrl: null};
});
}
render() {
const {classes} = this.props;
const {fileUrl} = this.state;
return (
<Paper className={classes.media}>
{fileUrl &&
<div className={classes.imageWrapper}>
<IconButton aria-label="Clear" className={classes.iconButton} onClick={() => this.removeImage()}>
<ClearIcon/>
</IconButton>
<img src={fileUrl} className={classes.image}/>
</div>
}
<input
accept="image/*"
className={classes.input}
id="upload-file"
type="file"
onChange={(event) => this.handleChange(event)}
/>
<label htmlFor="upload-file">
<Button component="span">
Add media...
</Button>
</label>
</Paper>
);
}
}