- 所有的react元素都有基于dom事件的属性,例如按钮元素有一个onClick属性,还有双击事件、鼠标移入事件(onKey...)。
- 处理onClick事件:
class Counter extends Component {
state = {
count: 0,
};
handleIncrement() {
console.log('Increment Clicked');
}
render() {
return (
<div>
<button onClick={this.handleIncrement} className='btn btn-secondary btn-sm'>Increment</button>
</div>
);
}
}
- 值得注意的是,我们在"onClick={this.handleIncrement()}"中并没有调用方法,只是传入了一个引用。这与在js中的处理方式不同:在写行内代码的时候,我们直接调用 js 函数。
绑定事件句柄
- 如果我们想要在函数handleIncrement()中增加count的值,就需要绑定事件句柄了,因为我们在handleIncrement()中无法访问this。
- 无法访问的原因:在 js 中,如果函数被以对象的方法调用(obj.method()),this总是返回那个对象的引用,但是,如果函数被以独立函数的方法调用(function()),this会返回window对象的引用。但是如果严格模式开启了,会返回未定义,所以handleIncrement()中无法访问this。
- 我们可以用bind来解决这个问题:
class Counter extends Component {
state = {
count: 0,
};
constructor() {
super();
this.handleIncrement = this.handleIncrement.bind(this);
}
handleIncrement() {
console.log('Increment Clicked',this);
}
render() {
return (
<div>
<button onClick={this.handleIncrement} className='btn btn-secondary btn-sm'>Increment</button>
</div>
);
}
- constructor() 中的bind方法会返回一个handleIncrement 方法的新实例,那个实例中的this永远指向现在constructor中的this对象(Counter),不管handleIncrement 方法被如何调用,它的this都永远指向现在这个对象。
- 保存修改,返回浏览器,点击button,我们可以看到this指向了counter,此时,我们就可以操作state属性了。
- 以上是一种绑定this的方法,但是这个方法有点麻烦,每次都要调用构造函数,还要调父类构造器(super()),每次都要这样来一遍,其实还有另一种方法:
我们可以把handleIncrement 函数改写为剪头函数,剪头函数是不会重新绑定this的,只继承this的关系。所以:
class Counter extends Component {
state = {
count: 0,
};
handleIncrement = () => {
console.log('Increment Clicked',this);
}
render() {
return (
<div>
<button onClick={this.handleIncrement} className='btn btn-secondary btn-sm'>Increment</button>
</div>
);
}
仅仅将handleIncrement 改为剪头函数,就解决了我们的问题,比手动绑定的方法简单多了,不得不感叹剪头函数的强大!
网友评论