我正在尝试构建一个类似于the one seen here的Showcase
组件,其中用户在滚动时浏览不同的内容:
我通过使用一些CSS来修复此部分:
.sticky {
position: sticky;
}
.top-0 {
top: 0;
}
应用于我的HTML:
<section
ref={(r) => this.ref = r}
classname={`vh-500 bg-near-white z-max pv6-ns pv3 bg-near-white min-vh-100
...
`}>
<div classname='sticky top-0 vh-100'>
在我的HTML元素上使用ref
,通过查看Showcase
与该组件本身的顶部和底部之间的关系,得出scrollY
组件粘滞的区域:
componentDidmount() {
if (this.ref) {
this.setState(
{
firstThreshold: this.ref.getBoundingClientRect().top,secondThreshold: window.innerHeight * amount
},// tslint:disable-next-line:no-console
() => console.log(this.state,"state")
);
}
window.addEventListener("scroll",this.handleScroll);
}
然后在我的handleScroll()
函数中,我们在滚动浏览Showcase
组件时检测到了
// if we're scrolling through the Showcase component
if (scrollY >= firstThreshold && scrollY <= secondThreshold) {
...
}
现在这是我迷失的地方:
我通过将视口高度乘以我要在组件中显示的故事的章节数量来获得组件的高度:
const chapters = [
{
content: 'Signs up',title: '',},{
content: 'Receives request',{
content: 'Gets a shit,rude requests from a person with 0 rating',{
content: 'Blocks them',{
content: 'Gets a nice request from a person who’s rated 5 stars',{
content: 'They agree on terms and accept the request',{
content: 'Time elapses',{
content: 'Thanks them for the time,gives them 5 stars',]
const amount = chapters.length
在我的handleScroll()
函数中,我试图确定用户滚动显示哪一章,但是我不确定如何到达。这是我现在拥有的:
for (let i = 0; i < amount; i++) {
// tslint:disable-next-line:no-console
console.log(i,"i");
if (scrollY >= (firstThreshold + sectionThreshold) * i) {
// tslint:disable-next-line:no-console
console.log(sectionThreshold * i,"sectionThreshold * i");
this.setState({ currentChapter: i },() => {
// tslint:disable-next-line:no-console
console.log(
`scrolling inside section: ${this.state.currentChapter}`
);
});
}
}
我要实现的目标:
- 在用户滚动浏览页面时显示每一章
我该怎么做?