why react component bind this in constructor

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

In many react compon【转载请注明来源】原创内容,盗版必究。ent’s construc【转载请注明来源】【关注微信公众号:wwwtangshuangnet】tor, developers alwa本文版权归作者所有,未经授权不得转载。【版权所有】唐霜 www.tangshuang.netys bind its methods 本文版权归作者所有,未经授权不得转载。【本文首发于唐霜的博客】with this, like:

本文作者:唐霜,转载请注明出处。【版权所有】唐霜 www.tangshuang.net【版权所有,侵权必究】
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著作权归作者所有,禁止商业用途转载。原创内容,盗版必究。?

【版权所有,侵权必究】【关注微信公众号:wwwtangshuangnet】【原创不易,请尊重版权】

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转载请注明出处:www.tangshuang.net【原创不易,请尊重版权】 your render, you al【本文首发于唐霜的博客】【原创内容,转载请注明出处】way use it as onClic【未经授权禁止转载】【未经授权禁止转载】k callback function,【原创不易,请尊重版权】未经授权,禁止复制转载。 this is why this is未经授权,禁止复制转载。【访问 www.tangshuang.net 获取更多精彩内容】 not point to instan【转载请注明来源】本文版权归作者所有,未经授权不得转载。ce of this component【版权所有,侵权必究】转载请注明出处:www.tangshuang.net. Let’s look i未经授权,禁止复制转载。【未经授权禁止转载】nto this code:

【作者:唐霜】【访问 www.tangshuang.net 获取更多精彩内容】转载请注明出处:www.tangshuang.net著作权归作者所有,禁止商业用途转载。
<a href="" onclick="alert(this.href)">click</a>

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

本文版权归作者所有,未经授权不得转载。【关注微信公众号:wwwtangshuangnet】
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著作权归作者所有,禁止商业用途转载。原创内容,盗版必究。 in say as want you 【版权所有,侵权必究】【本文首发于唐霜的博客】want.

【版权所有】唐霜 www.tangshuang.net本文作者:唐霜,转载请注明出处。【作者:唐霜】