react类组件的事件为什么需要绑定this?

这个问题其实在一年多以前吧,我就搞清楚了,结果已经很久没用react的类组件了,结果现在用了,发现自己忘了为什么要绑定,所以写一下这篇文章做笔记。
这里要清楚javascript中的this指向的问题。
例子

class App extends PureComponent {
  state = {
    count: 1
  }

  increase() {
    this.setState({
      count: this.state.count + 1
    })
  }

  render() {
    const { count } = this.state
    return <div onClick={this.increase}>{count}</div>
  }
}

你会发现它报错了。
这是为什么呢?
在进行props传值的时候,你相当于就是把值赋给了那个props,上面的代码与下面的代码一样。

const {count} = this.state;
const {increase} = this;
return <div onClick={increase}>{count}</div>

你看出来了吧。也就说react执行函数的时候,就是执行函数increase(event),而不是this.increase(event)。所以this指向的是undefined,非严格模式指向全局对象。
那么官方就提供了以下几种写法。
第一种:强烈推荐

class App extends PureComponent {
  state = {
    count: 1
  }

  increase = () => {
    this.setState({
      count: this.state.count + 1
    })
  }

  render() {
    const { count } = this.state
    return <div onClick={this.increase}>{count}</div>
  }
}

第二种:也不错。

class App extends PureComponent {
  state = {
    count: 1
  }

  constructor(props) {
    super(props);
    this.increase = this.increase.bind(this);
  }

  increase() {
    this.setState({
      count: this.state.count + 1
    })
  }

  render() {
    const { count } = this.state
    return <div onClick={this.increase}>{count}</div>
  }
}

第三种:不推荐
每次组件重渲染时都会重新调用bind返回一个新的函数。

class App extends PureComponent {
  state = {
    count: 1
  }

  increase() {
    this.setState({
      count: this.state.count + 1
    })
  }

  render() {
    const { count } = this.state
    return <div onClick={this.increase.bind(this)}>{count}</div>
  }
}

每天进步一点点,过了一段时间,你就会发现你比之前提高了很多。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值