【问题标题】:How can I access the 'this' in a read.onloadend in a React component?如何在 React 组件的 read.onloadend 中访问“this”?
【发布时间】:2018-08-12 16:29:10
【问题描述】:

我正在尝试读取用户在 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);
  }

【问题讨论】:

  • 请在此处查看工作示例codepen.io/santoshshinde2012/pen/XZwgLJ
  • 如果以下答案解决了您的问题,请将任何人标记为已接受并点赞。这样人们就可以继续解决其他人的问题。

标签: javascript reactjs file upload


【解决方案1】:

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

【讨论】:

  • 谢谢!这是完美的!箭头函数是最简单的解决方案。
【解决方案2】:

由于上下文更改 (this),它在 onload 回调中失败。 JavaScript 原生地改变回调中的上下文。在您的 onload 情况下,这与 reader 相同。

解决方案1:使用arrow operator (() =&gt;)。

Solution2:在this的父范围内分配that变量。

使用以下代码

  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

希望对你有帮助!!

【讨论】:

    【解决方案3】:

    由于您无权访问 this 内部。您必须按照以下方式实现它。

    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>
                    
                    
                    

    【讨论】:

      猜你喜欢
      • 2022-09-23
      • 2022-12-09
      • 1970-01-01
      • 2016-12-24
      • 2017-11-12
      • 2016-08-21
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      相关资源
      最近更新 更多