Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript &引用;TypeError:无法读取属性';州';“未定义”的定义;_Javascript_Reactjs - Fatal编程技术网

Javascript &引用;TypeError:无法读取属性';州';“未定义”的定义;

Javascript &引用;TypeError:无法读取属性';州';“未定义”的定义;,javascript,reactjs,Javascript,Reactjs,我试图在reactjs中上传一个文件,我想在控制台中显示,但当我点击upload按钮时,它给了我一个提示 “TypeError:无法读取未定义的属性'state'” 这是我的密码: constructor(props) { super(props); this.state = { selectedFile: null }; this.fileSelectedHandler = this.fileSelectedHandler.bind(this); } fileSele

我试图在reactjs中上传一个文件,我想在控制台中显示,但当我点击upload按钮时,它给了我一个提示

“TypeError:无法读取未定义的属性'state'”

这是我的密码:

constructor(props) {
        super(props);

this.state = {
  selectedFile: null
};

this.fileSelectedHandler = this.fileSelectedHandler.bind(this);
}

fileSelectedHandler(event) {
  this.setState({
    selectedFile: event.target.files[0]
  })
}

handleUpload() {
  console.log(this.state.selectedFile)
}
render() {
 return (
    <div class="group">
      <input type="file" name="file" id="file" onChange={this.fileSelectedHandler} />
      <button onClick={this.handleUpload}> Upload </button>
    </div>
    )
}
构造函数(道具){
超级(道具);
此.state={
selectedFile:空
};
this.fileSelectedHandler=this.fileSelectedHandler.bind(this);
}
fileSelectedHandler(事件){
这是我的国家({
selectedFile:event.target.files[0]
})
}
handleUpload(){
console.log(this.state.selectedFile)
}
render(){
返回(
上传
)
}

我在以下位置收到错误:
console.log(this.state.selectedFile)

有两种方法可以解决此问题:将handleUpload绑定到正确的内容,或以以下格式定义函数

handleUpload = () => {
console.log(this.state.selectedFile)
}

你必须在构造函数中将
handleUpload
绑定到
this
,就像你在
fileSelectedHandler
方法中所做的那样。你在声明状态之前调用构造函数函数和超级方法吗?你草率地用构造函数的一半粘贴了你的代码,伙计们,我做了一个更新,我忘了放构造函数和超级方法,现在我已经更新了代码。谢谢,兄弟,它成功了!