我正在尝试读取用户在 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});
}
}
关于javascript - 如何在 React 组件的 read.onloadend 中访问 'this' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49103322/