如何在 React 组件的 read.onloadend 中访问“this”?

Jos*_*oad 1 javascript upload file reactjs

我正在尝试读取用户在 React 组件中上传的文件,并将 React 组件的状态设置为文件内容。但是,在read.onloadend回调函数中,我无法通过this.

这是实际的表单部分(我正在使用 react-bootstrap)

      <FormGroup>
          <FormControl
            id="fileUpload"
            type="file"
            accept=".txt"
            onChange={this.handleSubmit.bind(this)}
          />
      </FormGroup>
Run Code Online (Sandbox Code Playgroud)

这是我处理提交的功能:

  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);
  }
Run Code Online (Sandbox Code Playgroud)

Agn*_*ney 6

只需使用箭头函数。这样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});
    }
  }
Run Code Online (Sandbox Code Playgroud)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this