[英]How call a function from addEventListener in ReactJS?
我在ReactJS中做无限滚动,但遇到麻烦了!
加载组件后,执行以下操作:
componentDidMount() {
window.addEventListener('scroll', function() {
var h = this.innerHeight;
var j = document.documentElement.scrollHeight;
var k = document.documentElement.scrollTop;
if ((h + k) >= j - 150) {
loadPhotos();
}
});
}
而且,作为一种魔术,我没有定义“ loadPhotos()”。 我不能使用this.loadPhotos(),因为它引用的是窗口(没有loadPhotos())。
我在Constructor()方法中初始化loadPhotos():
this.loadPhotos = this.loadPhotos.bind(this);
我的loadPhotos()是在Constructor()方法之外定义的,我的意思是在类主体中定义。
有人可以帮我吗? 感谢大伙们!
componentDidMount() {
window.addEventListener('scroll', () => { // arrow boys
var h = window.innerHeight;
var j = document.documentElement.scrollHeight;
var k = document.documentElement.scrollTop;
if ((h + k) >= j - 150) {
this.loadPhotos();
}
});
}
使用箭头函数作为回调,这将引用组件的实例。
因为回调中的原始this
引用了window
,所以您还需要将this.innerHeight
更改为window.innerHeight
。
componentDidMount() {
window.addEventListener('scroll', () => { // arrow function
var h = window.innerHeight;
var j = document.documentElement.scrollHeight;
var k = document.documentElement.scrollTop;
if ((h + k) >= j - 150) {
this.loadPhotos(); // now you can use this
}
});
}
如果要使用自己的方式,则可以使用let _self = this
来解决问题。
像这样
componentDidMount() {
let _self = this;
window.addEventListener('scroll', function() {
var h = window.innerHeight;
var j = document.documentElement.scrollHeight;
var k = document.documentElement.scrollTop;
if ((h + k) >= j - 150) {
_self.loadPhotos();
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.