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:

【本文首发于唐霜的博客】【未经授权禁止转载】转载请注明出处:www.tangshuang.net【未经授权禁止转载】
export default class MyComponent extends Component {
  constructor() {
    this.say = this.say.bind(this)
  }
  ...
}

This sentence seems 【本文首发于唐霜的博客】【未经授权禁止转载】to be stupid. Is thi转载请注明出处:www.tangshuang.net【未经授权禁止转载】s regulated by react著作权归作者所有,禁止商业用途转载。著作权归作者所有,禁止商业用途转载。?

【作者:唐霜】【访问 www.tangshuang.net 获取更多精彩内容】原创内容,盗版必究。【版权所有】唐霜 www.tangshuang.net

No!

【未经授权禁止转载】【版权所有,侵权必究】本文作者:唐霜,转载请注明出处。

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

著作权归作者所有,禁止商业用途转载。著作权归作者所有,禁止商业用途转载。未经授权,禁止复制转载。
<a href="" onclick="alert(this.href)">click</a>

You know what this p转载请注明出处:www.tangshuang.net【本文首发于唐霜的博客】oint to here, so whe本文版权归作者所有,未经授权不得转载。转载请注明出处:www.tangshuang.netn you use a componen【未经授权禁止转载】本文作者:唐霜,转载请注明出处。t method as a event 转载请注明出处:www.tangshuang.net本文版权归作者所有,未经授权不得转载。callback function, t【未经授权禁止转载】著作权归作者所有,禁止商业用途转载。his in the function 未经授权,禁止复制转载。【版权所有】唐霜 www.tangshuang.netdoes not referer to 【本文首发于唐霜的博客】本文版权归作者所有,未经授权不得转载。the instance of comp【版权所有,侵权必究】本文版权归作者所有,未经授权不得转载。onent. So another wa未经授权,禁止复制转载。【原创不易,请尊重版权】y to solve this prob转载请注明出处:www.tangshuang.net【关注微信公众号:wwwtangshuangnet】lem is to bind this 著作权归作者所有,禁止商业用途转载。【本文首发于唐霜的博客】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【未经授权禁止转载】【原创内容,转载请注明出处】 in say as want you 【本文首发于唐霜的博客】【访问 www.tangshuang.net 获取更多精彩内容】want.

【关注微信公众号:wwwtangshuangnet】【作者:唐霜】【原创内容,转载请注明出处】