如何绑定.onload函数

时间:2019-04-21 20:31:56

标签: javascript reactjs ecmascript-6 binding onload

我正在尝试在客户端上载和读取文本文件。我正在使用FileReader,但是我在其onload函数中遇到麻烦,该函数要设置状态变量,但我不能。 结果:TypeError:this.setState不是函数


loadVoters(){

    console.log("this function is called after file is uploaded");
    var file = document.getElementById('uploadedFile').files[0];
    let fileContents;
    var fileReader = new FileReader();
    fileReader.onload = function(e){
      fileContents = e.target.result;
      //This displays contents on the page, so works
      document.getElementById('fileContentsDisplay').innerHTML=
fileContents;
      //This fails "this.setState is not a function"
      this.setState({
        contents: fileContents
      });


    }

    fileReader.readAsText(file, "UTF-8");
    //Prints the value of fileContents as undefined
    console.log("see the value of fileContents: ", fileContents);
    console.log("see the state variable here: ", this.state.contents);
  }

0 个答案:

没有答案