我想在按下上载按钮后在DOM上呈现图像。我的尝试是将imageSource的状态设置为file并在dom中呈现该状态,但是我收到“ JSON在位置1处出现意外令牌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;
答案 0 :(得分:0)
读者JSON.parse()
事件处理程序中对load
的调用引发此错误,因为file
变量不是字符串。
要通过imageSource
更新组件的setState()
状态,可以进行以下调整:
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标记中,考虑通过更新<img/>
属性并像这样调整右括号来调整src
元素:
<img className="mx-auto d-block pb-2" src={this.state.imageSource} alt="" />