gpt4 book ai didi

javascript - 当每个 div 滚动到 View 和更新状态时触发事件

转载 作者:行者123 更新时间:2023-11-30 06:12:03 25 4
gpt4 key购买 nike

每当其中一个子组件滚动到 View 中时,我试图让我的一个 React 组件触发一个事件。为此,我将子级的引用传递给父级,然后将窗口的位置与“currentCard”的引用进行比较。一旦窗口到达 currentCard 的底部,它就会将 1 添加到 currentCard 的状态。问题是,当我设置状态时,它发生的速度不够快,因此滚动事件会触发多个设置状态,然后超出范围。这是我处理滚动的方式:

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。当该值变为负数时,表示它在视口(viewport)之外,您可以将状态设置为下一个元素。

下面添加了一个示例 SO 片段。一旦元素离开 View ,您就可以向下滚动并在控制台中查看状态更新。希望这对您有所帮助!

class App extends React.Component {
state = { cardRefs: [], currentCard: 0 };
myRef1 = React.createRef();
myRef2 = React.createRef();
myRef3 = React.createRef();

componentDidMount() {
window.addEventListener("scroll", this.handleScroll);
this.setState({
cardRefs: [this.myRef1, this.myRef2, this.myRef2]
});
}

handleScroll = () => {
let { cardRefs, currentCard } = this.state;
if (cardRefs[currentCard].current.getBoundingClientRect().bottom < 0) {
console.log("bottom");
this.setState(prevState => {
return {
currentCard:
currentCard + 1 >= cardRefs.length
? cardRefs.length - 1
: currentCard + 1
};
});
}
};
render() {
console.log("Current Card", this.state.currentCard);
return (
<div>
<div
ref={this.myRef1}
style={{ height: "500px", backgroundColor: "red" }}
></div>
<div
ref={this.myRef2}
style={{ height: "500px", backgroundColor: "green" }}
></div>
<div
ref={this.myRef3}
style={{ height: "500px", backgroundColor: "blue" }}
></div>
</div>
);
}
}


ReactDOM.render(
<App />,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

关于javascript - 当每个 div 滚动到 View 和更新状态时触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58328428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com