Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/416.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将每个div滚动到查看和更新状态时触发事件_Javascript_Reactjs - Fatal编程技术网

Javascript 将每个div滚动到查看和更新状态时触发事件

Javascript 将每个div滚动到查看和更新状态时触发事件,javascript,reactjs,Javascript,Reactjs,我试图让我的一个React组件在每次将一个子组件滚动到视图中时触发一个事件。为此,我将引用从子对象传递到父对象,然后将窗口的位置与“currentCard的”引用进行比较。一旦窗口到达currentCard的底部,它将向currentCard的状态添加1。问题是,当我设置state时,它的发生速度不够快,所以scroll事件触发多个setState,然后超出范围。以下是我如何处理滚动: componentDidMount(){ window.addEventListener('scrol

我试图让我的一个React组件在每次将一个子组件滚动到视图中时触发一个事件。为此,我将引用从子对象传递到父对象,然后将窗口的位置与“currentCard的”引用进行比较。一旦窗口到达currentCard的底部,它将向currentCard的状态添加1。问题是,当我设置state时,它的发生速度不够快,所以scroll事件触发多个setState,然后超出范围。以下是我如何处理滚动:

componentDidMount(){
    window.addEventListener('scroll', (e) => this.handleScroll(e))
}

handleScroll = (e) => {
    let { cardRefs, currentCard } = this.state;
    let currentCardPos = cardRefs[currentCard].current.getBoundingClientRect().height

    if ( window.pageYOffset >= currentCardPos ){
      console.log('bottom')
      this.setState(prevState => ({
        currentCard: prevState.currentCard + 1
      }))
    }
}
cardRefs是从子组件向上传递的refs数组,currentCard只是一个索引,用于跟踪用户当前在页面上的卡


必须有更好的方法,我只是不知道从哪里开始

在本例中,您使用的是
getBoundingClientRect().height
,它总是一个常量。例如,如果高度设置为500px,则它始终返回500px。window.offsetY穿过500px后,它会一直递增,直到超出边界

相反,您可以尝试使用
getBoundingClientRect().bottom
。当该值变为负值时,表示其超出视口,您可以将状态设置为下一个元素

下面添加了一个示例代码段。您可以向下滚动,并在元素离开视图后立即在控制台中看到状态更新。希望这有帮助

类应用程序扩展了React.Component{
状态={cardRefs:[],当前卡:0};
myRef1=React.createRef();
myRef2=React.createRef();
myRef3=React.createRef();
componentDidMount(){
window.addEventListener(“滚动”,this.handleScroll);
这是我的国家({
cardRefs:[this.myRef1,this.myRef2,this.myRef2]
});
}
handleScroll=()=>{
设{cardRefs,currentCard}=this.state;
if(cardRefs[currentCard].current.getBoundingClientRect().bottom<0){
控制台日志(“底部”);
this.setState(prevState=>{
返回{
当前卡:
currentCard+1>=cardRefs.length
?卡片参考长度-1
:当前卡+1
};
});
}
};
render(){
console.log(“当前卡”,this.state.currentCard);
返回(
);
}
}
ReactDOM.render(
,
document.getElementById(“根”)
);