why react component bind this in constructor

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

In many react compon本文作者:唐霜,转载请注明出处。【原创不易,请尊重版权】ent’s construc【原创不易,请尊重版权】【版权所有,侵权必究】tor, developers alwa著作权归作者所有,禁止商业用途转载。【访问 www.tangshuang.net 获取更多精彩内容】ys bind its methods 本文作者:唐霜,转载请注明出处。【访问 www.tangshuang.net 获取更多精彩内容】with this, like:

【作者:唐霜】未经授权,禁止复制转载。原创内容,盗版必究。
export default class MyComponent extends Component {
  constructor() {
    this.say = this.say.bind(this)
  }
  ...
}

This sentence seems 【原创不易,请尊重版权】【作者:唐霜】to be stupid. Is thi原创内容,盗版必究。【关注微信公众号:wwwtangshuangnet】s regulated by react著作权归作者所有,禁止商业用途转载。【作者:唐霜】?

【关注微信公众号:wwwtangshua【转载请注明来源】转载请注明出处:www.tangshuang.netngnet】转载请注明出处:www.tangshua本文作者:唐霜,转载请注明出处。著作权归作者所有,禁止商业用途转载。ng.net

No!

【本文受版权保护】未经授权,禁止复制转载。【本文首发于唐霜的博客】

In fact, react compo著作权归作者所有,禁止商业用途转载。转载请注明出处:www.tangshuang.netnent class follow ES本文版权归作者所有,未经授权不得转载。【版权所有】唐霜 www.tangshuang.net6 class std. The rea转载请注明出处:www.tangshuang.net原创内容,盗版必究。son to put this sent转载请注明出处:www.tangshuang.net未经授权,禁止复制转载。ence is because when【版权所有】唐霜 www.tangshuang.net【转载请注明来源】 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【本文首发于唐霜的博客】著作权归作者所有,禁止商业用途转载。 not point to instan原创内容,盗版必究。【本文首发于唐霜的博客】ce of this component【转载请注明来源】【未经授权禁止转载】. Let’s look i【版权所有】唐霜 www.tangshuang.net【未经授权禁止转载】nto this code:

【版权所有,侵权必究】未经授权,禁止复制转载。【访问 www.tangshuang.n【关注微信公众号:wwwtangshuangnet】原创内容,盗版必究。et 获取更多精彩内容】
<a href="" onclick="alert(this.href)">click</a>

You know what this p原创内容,盗版必究。【本文首发于唐霜的博客】oint to here, so whe未经授权,禁止复制转载。本文作者:唐霜,转载请注明出处。n you use a componen【作者:唐霜】本文作者:唐霜,转载请注明出处。t method as a event 著作权归作者所有,禁止商业用途转载。【版权所有】唐霜 www.tangshuang.netcallback function, t本文版权归作者所有,未经授权不得转载。本文作者:唐霜,转载请注明出处。his in the function 【版权所有】唐霜 www.tangshuang.net转载请注明出处:www.tangshuang.netdoes not referer to 本文版权归作者所有,未经授权不得转载。本文作者:唐霜,转载请注明出处。the instance of comp【版权所有,侵权必究】本文版权归作者所有,未经授权不得转载。onent. So another wa【转载请注明来源】【本文受版权保护】y to solve this prob著作权归作者所有,禁止商业用途转载。本文版权归作者所有,未经授权不得转载。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 未经授权,禁止复制转载。原创内容,盗版必究。want.

本文作者:唐霜,转载请注明出处。【关注微信公众号:wwwtangshua【转载请注明来源】【本文受版权保护】ngnet】