我在reactJS的componentWillMount上有一个Jquery函数:
$(document).ready(function(e) {
this.myFunction();
}
以及下面声明的箭头功能:
myFunction = () => {
alert("Jquery is ready!");
}
为什么我得到this.myFunction()不是函数错误?
[您正在另一个函数中调用this
,该函数未绑定到您的对象,因此更改了this
的范围。
您可以尝试
a)使函数成为箭头函数:
$(document).ready(() => this.myFunction());
b)将外部this
绑定到匿名函数中
$(document).ready(function(e) {
this.myFunction();
}.bind(this));
c)创建一个包含this
的变量>
var self = this; $(document).ready(function(e) { self.myFunction(); });
干杯!