Javascript 如何在";之外调用此.txt变量;reader.onload=功能显示(事件)";

Javascript 如何在";之外调用此.txt变量;reader.onload=功能显示(事件)";,javascript,reactjs,Javascript,Reactjs,我想在函数“reader.onload=function show(event)”之外获取this.txt变量……我试图在这里调用此变量。query“但我只获取未定义的值 showFile(){ if (window.File && window.FileReader && window.FileList && window.Blob) { var preview = document.getElementById('s

我想在函数“reader.onload=function show(event)”之外获取this.txt变量……我试图在这里调用此变量。query“但我只获取未定义的值

 showFile(){
    if (window.File && window.FileReader && window.FileList && window.Blob) {
         var preview = document.getElementById('show-text');
         var file = document.querySelector('input[type=file]').files[0];
         var reader = new FileReader()
         var textFile = /text.*/;
          var myArray = [];

         if (file.type.match(textFile)) {   
            reader.onload = function show (event) {
            //document.write(event.target.result); 
            myArray=(event.target.result.split('\n'))
            this.txt=myArray;
            alert(this.txt);
            }   
         }

            superagent.get('https://www.googleapis.com/customsearch/v1')
            .query({'key': this.apiKey,'num':10,'cx': this.cx ,'q':this.txt,'gl':'all'})
            .then((res) =>{

                console.log('value of show', this.show)
                console.log('response', res)
                let arr = res.body.items
            //   arr.map((value)=>{
            //      console.log('value', value)
            //      this.field =value
            //  })
                this.field = arr
                this.setState({
                    show: true
                })

            })
        reader.readAsText(file);
}
  }

您需要将
showFile()
绑定到实例,或者对其使用箭头形式:

showFile = () => {
// code here
}

请提供有关要在哪个范围内访问哪个变量的其他信息?请再次检查RenéCarannanteya,我这样做了,但它什么也不返回。它只在函数内、尝试调用函数外或if语句外时返回数组值,它返回null(无)。