why react component bind this in constructor

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

In many react compon【本文首发于唐霜的博客】本文作者:唐霜,转载请注明出处。ent’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?

【作者:唐霜】本文作者:唐霜,转载请注明出处。

No!

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

In fact, react compo【版权所有,侵权必究】【访问 www.tangshuang.net 获取更多精彩内容】nent class follow ES【关注微信公众号:wwwtangshuangnet】【作者:唐霜】6 class std. The rea【访问 www.tangshuang.net 获取更多精彩内容】【本文首发于唐霜的博客】son to put this sent【访问 www.tangshuang.net 获取更多精彩内容】【本文首发于唐霜的博客】ence is because when【版权所有】唐霜 www.tangshuang.net【访问 www.tangshuang.net 获取更多精彩内容】 you use this.say in【关注微信公众号:wwwtangshuangnet】原创内容,盗版必究。 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本文作者:唐霜,转载请注明出处。【本文受版权保护】nto this code:

【作者:唐霜】【作者:唐霜】
<a href="" onclick="alert(this.href)">click</a>

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

【关注微信公众号:wwwtangshuangnet】本文版权归作者所有,未经授权不得转载。

2017-09-30 2822

为价值买单,打赏一杯咖啡

本文价值28.22RMB