|
React 中,事件处理程序中,默认情况下,this为 undefined ,如果使用 this ,可以使用如下方法
第一种: 绑定事件处理程序时,使用bind方法绑定this 如: <button onClick ={ this.addComment.bind(this) }></button> 第二种: construtor() 方法中,使用 bind 方法绑定 this construtor () { super(); this.addComment = this.addComment.bind(this) } 第三种: 使用箭头函数,来定义事件处理程序 addComment = ()=>{ } 第四种: 如: <button onClick ={ ()=>{ this.addComment } }></button> |
|
|