首页 > 解决方案 > 无法读取未定义状态的属性

问题描述

我在单击按钮时无法读取未定义的属性“状态”。这是我的工作

constructor(props){
  super()

  this.state = {
    email:"",
    guestName:"",
    staffName:"",

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


  onSend(){
      let val = this.state
      console.log(val)
  }
render(){
return(
<Button variant="contained" color="primary" className={"send"} onClick={this.onSend}>
        Send
      </Button>)
   }  

我错过了什么?

标签: javascriptreactjs

解决方案


您的问题是,this在您的onSend()函数中不是指类,而是指调用该函数的元素(在您的情况下是Button元素)。

要解决此问题,您可以将函数更改为如下代码中的箭头函数,或者您可以将this引用(类)与.bind(this)(so onClick={this.onSend.bind(this)})绑定

constructor(props){
  super()

  this.state = {
    email:"",
    guestName:"",
    staffName:"",   
  };
}

onSend = () => {
    let val = this.state
    console.log(val)
}

render(){
  return(
    <Button variant="contained" color="primary" className={"send"} onClick={this.onSend}>
        Send
    </Button>)
 }

推荐阅读