Sta*_*edo 3 javascript 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();
}
});
}
Run Code Online (Sandbox Code Playgroud)
而且,作为一种魔法,我“未定义 loadPhotos()”。我不能使用 this.loadPhotos() 因为它指的是窗口(没有 loadPhotos())。
我在 constructor() 方法中初始化我的 loadPhotos():
this.loadPhotos = this.loadPhotos.bind(this);
Run Code Online (Sandbox Code Playgroud)
我的 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();
}
});
}
Run Code Online (Sandbox Code Playgroud)
使用箭头函数作为回调,这将引用组件的实例。
因为原来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
}
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1664 次 |
| 最近记录: |