why react component bind this in constructor

广告位招租
扫码页面底部二维码联系

In many react compon【版权所有,侵权必究】【版权所有】唐霜 www.tangshuang.netent’s construc【未经授权禁止转载】【转载请注明来源】tor, developers alwa本文作者:唐霜,转载请注明出处。著作权归作者所有,禁止商业用途转载。ys bind its methods 【未经授权禁止转载】【版权所有,侵权必究】with this, like:

【未经授权禁止转载】本文作者:唐霜,转载请注明出处。本文作者:唐霜,转载请注明出处。
export default class MyComponent extends Component {
  constructor() {
    this.say = this.say.bind(this)
  }
  ...
}

This sentence seems 转载请注明出处:www.tangshuang.net【未经授权禁止转载】to be stupid. Is thi著作权归作者所有,禁止商业用途转载。【未经授权禁止转载】s regulated by react转载请注明出处:www.tangshuang.net【原创不易,请尊重版权】?

【转载请注明来源】【转载请注明来源】

No!

本文作者:唐霜,转载请注明出处。【访问 www.tangshuang.net 获取更多精彩内容】

In fact, react compo【原创内容,转载请注明出处】本文作者:唐霜,转载请注明出处。nent class follow ES本文版权归作者所有,未经授权不得转载。【原创内容,转载请注明出处】6 class std. The rea【作者:唐霜】未经授权,禁止复制转载。son to put this sent【本文受版权保护】【版权所有,侵权必究】ence is because when【转载请注明来源】本文版权归作者所有,未经授权不得转载。 you use this.say in著作权归作者所有,禁止商业用途转载。著作权归作者所有,禁止商业用途转载。 your render, you al原创内容,盗版必究。【访问 www.tangshuang.net 获取更多精彩内容】way use it as onClic本文作者:唐霜,转载请注明出处。【本文首发于唐霜的博客】k callback function,【本文受版权保护】著作权归作者所有,禁止商业用途转载。 this is why this is著作权归作者所有,禁止商业用途转载。转载请注明出处:www.tangshuang.net not point to instan【原创不易,请尊重版权】本文版权归作者所有,未经授权不得转载。ce of this component【版权所有,侵权必究】【版权所有,侵权必究】. Let’s look i【转载请注明来源】【版权所有】唐霜 www.tangshuang.netnto this code:

【原创不易,请尊重版权】【版权所有,侵权必究】转载请注明出处:www.tangshuang.net著作权归作者所有,禁止商业用途转载。
<a href="" onclick="alert(this.href)">click</a>

You know what this p著作权归作者所有,禁止商业用途转载。原创内容,盗版必究。oint to here, so whe未经授权,禁止复制转载。【版权所有】唐霜 www.tangshuang.netn you use a componen【原创内容,转载请注明出处】本文版权归作者所有,未经授权不得转载。t method as a event 【访问 www.tangshuang.net 获取更多精彩内容】【访问 www.tangshuang.net 获取更多精彩内容】callback function, t著作权归作者所有,禁止商业用途转载。原创内容,盗版必究。his in the function 【作者:唐霜】【原创不易,请尊重版权】does not referer to 【原创内容,转载请注明出处】【原创内容,转载请注明出处】the instance of comp未经授权,禁止复制转载。著作权归作者所有,禁止商业用途转载。onent. So another wa转载请注明出处:www.tangshuang.net【版权所有,侵权必究】y to solve this prob未经授权,禁止复制转载。【访问 www.tangshuang.net 获取更多精彩内容】lem is to bind this 【转载请注明来源】【访问 www.tangshuang.net 获取更多精彩内容】when you use the met本文作者:唐霜,转载请注明出处。【未经授权禁止转载】hod, like:

本文版权归作者所有,未经授权不得转载。著作权归作者所有,禁止商业用途转载。【转载请注明来源】
export default class MyComponent extends Component {
  constructor() {
    // do not use bind sentence
  }
  render() {
    return <a onClick={this.say.bind(this)}>click</a>
  }
}

Now you can use this本文版权归作者所有,未经授权不得转载。【版权所有】唐霜 www.tangshuang.net in say as want you 【原创内容,转载请注明出处】著作权归作者所有,禁止商业用途转载。want.

未经授权,禁止复制转载。【关注微信公众号:wwwtangshuangnet】著作权归作者所有,禁止商业用途转载。