react中记得给添加在元素上的事件,绑定this的指向。

 

 

 

-----------------------------------------------------------------------------------------------------------

 如果总是在构造函数中绑定this指向,惹恼了你。可以使用下面两种不是很推荐的方式。

1.

2.

 

 

 

 

 

You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClickthis will be undefined when the function is actually called.

This is not React-specific behavior; it is a part of how functions work in JavaScript. Generally, if you refer to a method without () after it, such as onClick={this.handleClick}, you should bind that method.

If calling bind annoys you, there are two ways you can get around this. If you are using the experimental public class fields syntax, you can use class fields to correctly bind callbacks:

posted @ 2020-03-05 16:56  ladybug7  阅读(437)  评论(0编辑  收藏  举报