其他分享
首页 > 其他分享> > react中记得给添加在元素上的事件,绑定this的指向。

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:

标签:JavaScript,指向,bind,绑定,method,react,callbacks,handleClick,class
来源: https://www.cnblogs.com/ladybug7/p/12421188.html