无法读取未定义状态的属性

 收藏

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

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>)
   }  

我想念什么?

回复
  • 你太小 回复

    当您将事件处理程序定义为类中的非箭头函数(如onSend())时,this关键字未绑定到组件的上下文。请尝试以下任一方法:

    1)绑定它,看起来您差不多完成了:

    constructor(props){
      super()
    
      this.state = {
        email:"",
        guestName:"",
        staffName:"",
    
      };
       this.onSend = this.onSend.bind(this)
    }
    

    2)将onSend()转换为箭头函数。多亏了词法作用域,this关键字现在将指向onSend的所有者,后者是类组件本身。

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

    3)将this关键字绑定到事件处理程序中

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

  • wnatus 回复

    Your issue is that this in your onSend() function does not refer to the class, but to the element that called the function (in your case the Button element).

    To fix this you can change the function to an arrow function like in the code below or you can bind the this reference (the class) with .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>)
     }