ReactJS bind(this)

前端 未结 2 933
粉色の甜心
粉色の甜心 2020-12-06 22:51

I\'m following a tutorial to update states in ReactJS. I came across this line in the tutorial this.updateLanguage = this.updateLanguage.bind(this) and I don\'t

相关标签:
2条回答
  • 2020-12-06 23:34

    If you not getting the bind(this) in constructor then its not but one of the way to avoid binding in render

    Now why we need bind(this) in render let say we generally use onChange={this.handleChange.bind(this)}

    These approaches assume that you’re declaring React components using ES6 classes. If you use an ES6 class, React no longer autobinds.

    So, this is the One way to resolve this is to call bind in render.

    0 讨论(0)
  • 2020-12-06 23:42

    DOM callbacks such as click events will set the this context to the DOM element itself, in this case the li. Try removing the part you don't understand and see what happens - you'll see something like this.setState is not defined, because that function isn't defined in the context of the li element (it's basically looking for li.setState).

    What bind is doing on that line is ensuring that whenever that function gets called, it will get called with the this context we want, in this case the Popular component - e.g. Popular.setState.

    These days it's getting more and more common to see folks just using fat arrow syntax as a shorthand to preserve the this context - e.g. in this case onClick={ () => this.updateLanguage(lang) }.

    (note for those concerned about performance: the fat arrow approach is cleaner but somewhat controversial since it's repeatedly declaring the function on every single render. That said, some folks claim there is minimal or no significant performance impact.)

    0 讨论(0)
提交回复
热议问题