使用 this.setState() 将 Blob 渲染为 State,并在 DOM 中渲染 Image



我想在按下上传按钮后在 DOM 上渲染图像。我的尝试是将 imageSource 的状态设置为文件并在 dom 中呈现,但我收到"位置 1 处 JSON 中的意外令牌 o"错误。关于如何找到解决方法的任何帮助?我开始编写的额外细节只是为了满足 stackoverflow 的细节限制。我已经差不多解释了自己。

import React, { Component } from 'react';
import './Generator.css';

class Generator extends Component {
constructor(props){
super(props);
this.state = {
imageSource: './image/image.svg'
}
this.fileUpload = this.fileUpload.bind(this)
this.fileSelected = this.fileSelected.bind(this)
}
fileUpload(){
var preview = document.querySelector('img');
var file    = document.querySelector('input[type=file]').files[0];
var reader  = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
this.setState({imageSource: JSON.parse(file) }) 
console.log(this.state.imageSource)
console.log(file)
}, false);
if (file) {
reader.readAsDataURL(file);
}    }
fileSelected(){
console.log(this.state.imageSource)
}
render() {
return (
<div>
<div className="container">
<div className="card-body">
<h6 className="card-subtitle text-muted pt-1">Generate a Colin Kaepernick Nike Campaign Meme Fast and Easy</h6>
</div>
<img className="mx-auto d-block pb-2" src={require(`${this.state.imageSource}`)}  alt=""></img>  
</div>
<form>
<fieldset>
<div className="form-group pt-5">
<label htmlFor="quote">Type in your quote</label>
<textarea className="form-control" id="quote" rows="2" placeholder="Type your quote here..." ></textarea>
</div>   
</fieldset>
</form>
<div className="btn-toolbar d-block justify-content-center p-2">  
<div className="btn-group mr-2">
<button onClick={() => this.fileUpload.click()} type="button" className="btn btn-primary">UPLOAD IMAGE</button>
</div>
<div className="btn-group mr-2">
<button type="button" className="btn btn-success">GENERATE</button>
</div>   
<div className="form-group">
<input ref={fileUpload => this.fileUpload = fileUpload} style={{display: 'none'}} type="file" onChange={this.fileUpload}/>              
</div>           
</div>
</div>
);
}
}
export default Generator;

在读取器load事件处理程序中调用JSON.parse()会引发此错误,因为file变量不是字符串。

要通过setState()更新组件的imageSource状态,您可以进行以下调整:

reader.addEventListener("load", function () {
preview.src = reader.result;
this.setState({imageSource: file })  // Remove JSON.parse
console.log(this.state.imageSource)
console.log(file)
}, false);

同样在 HTML 标记中,请考虑通过更新src属性并调整右括号来调整<img/>元素,如下所示:

<img className="mx-auto d-block pb-2" src={this.state.imageSource}  alt="" />

相关内容

最新更新