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

问题描述 投票:0回答:3

我正在尝试读取用户在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);
  }
javascript reactjs file upload
3个回答
2
投票

只需使用箭头功能。这样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});
    }
  }

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


1
投票

由于更改了上下文(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的工作示例。

希望对你有帮助!!


0
投票

由于您无法访问此内部。您必须以下列方式实现它。

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>
                
                
                
© www.soinside.com 2019 - 2024. All rights reserved.