事件
onClick点击事件
- JSX中,onClick={this.函数名}来绑定事件
- this引用的问题,组件使用ES6写法,需要在构造函数里用bind绑定this,或用箭头函数
改变this的三种方法
1.通过箭头函数
onClick={()=>this.addName()}
2.使用bind绑定this到当前类中
onClick={this.addName.bind(this)
3.在construct构造函数中使用bind
class Register extends React.Component {
constructor(props) {
super(props)
this.login = this.login.bind(this)
}
login() {
...
}
render () {
return (
<Button onClick={this.login} type='primary'>登录</Button>
)
}
}
性能:
第一种在render中使用bind,每次每渲染一次render,bind都会执行一次
第二种,每渲染一次render,都会生成一个新的函数,函数不是简单的数据类型,它们都指向不同的地址,影响性能
推荐第三种写法,bind只会初始化的时候执行