我正在尝试读取用户在React组件中上传的文件,并将React组件的状态设置为文件内容。但是,在read.onloadend
回调函数中,我无法通过this
访问该状态。
这是实际的表单部分(我正在使用react-bootstrap)
<FormGroup>
<FormControl
id="fileUpload"
type="file"
accept=".txt"
onChange={this.handleSubmit.bind(this)}
/>
</FormGroup>
这是我处理提交的功能:
handleSubmit(e) {
e.preventDefault()
let inputtext;
let file = e.target.files[0];
let read = new FileReader();
read.readAsBinaryString(file);
read.onloadend = function(){
this.setState({filetext : read.result});
}
read.onloadend.bind(this);
}
只需使用箭头功能。这样this
不会改变。
handleSubmit(e) {
e.preventDefault()
let inputtext;
let file = e.target.files[0];
let read = new FileReader();
read.readAsBinaryString(file);
read.onloadend = () => {
this.setState({filetext : read.result});
}
}
由于更改了上下文(this
),它在onload回调中失败。 JavaScript本身改变了回调中的上下文。在onload的情况下,这与读者相同。
解决方案1:使用arrow operator(() =>
)。
解决方案2:在that
的父范围内分配this
变量。
使用以下代码
read.onloadend = () => {
this.setState({filetext : read.result});
}
要么
handleSubmit(e) {
e.preventDefault()
// assign parent scope to here
let that = this;
let inputtext;
let file = e.target.files[0];
let read = new FileReader();
read.readAsBinaryString(file);
read.onloadend = function(){
that.setState({filetext : read.result});
}
read.onloadend.bind(this);
}
请查看here的工作示例。
希望对你有帮助!!
由于您无法访问此内部。您必须以下列方式实现它。
handleSubmit(e) {
e.preventDefault()
let _this = this;
let inputtext;
let file = e.target.files[0];
let read = new FileReader();
read.readAsBinaryString(file);
read.onloadend = function(){
_this.setState({filetext : read.result});
console.log(read.result);
}
read.onloadend.bind(this);
}
<FormGroup>
<FormControl
id="fileUpload"
type="file"
accept=".txt"
onChange={this.handleSubmit.bind(this)}
/>
</FormGroup>