React中的this

class Button extends React.Component{
  constructor(props) {
    super(props);
  }
	
  increament() {
    this.setState({
      count: this.state.count + 1
    })
  }
	
  render() {
    return (<button onClick={ this.increament }>增加按钮</button>);
  }
}

这里会报错 Uncaught TypeError: Cannot read property 'setState' of undefined

JavaScript函数中的this不是在函数声明的时候,而是在函数运行的时候定义的

在JSX语法中: onClick={  function  }  onClick这个属性本身只是一个"中间变量"。将函数赋值给onClick这个中间变量,后面不仅要进行JSX语法转化,将JSX组件转换成Javascript对象,还要再将Javascript对象转换成真实DOM。把onClick作为中间变量,指向一个函数的时候,后面的一系列处理中,使用onClick这个中间变量所指向的函数,里面的this自然就丢失掉了,不是再指向对象实例了。

解决方法:

(1)在构造函数中增加

this.increament = this.increament.bind(this);

(2)或者是在render函数的事件中绑定

<button onClick={ this.increament.bind(this) }>增加按钮</button>

(3)利用箭头函数定义方法

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

(4)在引用时使用箭头函数

<button onClick={ () => this.increament() }>增加按钮</button> 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值