【问题标题】:React's this with onClick or onChange function [duplicate]用 onClick 或 onChange 函数反应这个 [重复]
【发布时间】:2018-04-20 17:46:01
【问题描述】:

我在我的反应组件中调用一个函数

<button onClick={this.createComment}>Submit Comment</button>

在我的 createComment 函数中,“this”由于某种原因未定义

createComment(event) {
    console.log('inside createComment')
    console.log('event', event)
    console.log('this', this)

    event.preventDefault()
  }

我需要在 createComment 函数中调用 this.setState。 如何让this 成为组件的 this??

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    改变这个:

    onClick={this.createComment}
    

    onClick={(e) => this.createComment(e)}
    

    onClick={this.createComment.bind(this)}
    

    注意:

    正如@rafahoro 评论的那样:

    你应该更喜欢在构造函数上绑定“this”:

    constructor() { 
         this.createComment = this.createComment.bind(this); 
    } 
    

    使用"onClick={(e) =&gt; this.createComment(e)}" 或类似名称,将 在每个 render() 调用上创建一个新函数。

    【讨论】:

    • 使用arrow function.bind(this) onClick={(e) =&gt; this.createComment(e)}
    • @ShubhamKhatri,谢谢
    • 您应该更喜欢在构造函数上绑定“this”:constructor() { this. createComment = 这个。 createComment.bind(this); } 使用 "onClick={(e) => this.createComment(e)}" 或类似的,会在每次调用 render() 时创建一个新函数。
    猜你喜欢
    • 2015-04-06
    • 2020-02-17
    • 2017-01-28
    • 2016-04-11
    • 2018-10-25
    • 2021-10-23
    • 2023-03-10
    • 2018-10-21
    相关资源
    最近更新 更多