我正在尝试在React中开发一个网页,以检测滚动当前位于哪个div
并更改该div中某些元素的样式。
在导航栏组件中,我已经打过一次
window.AddEventListener(..)
使用滚动侦听器和React对此实现进行引用
https://stackoverflow.com/a/47442272/3332734
因此无法在同一页面中两次调用它,因此我正在调用定义为3个
document.querySelector('.page-article-section')
HTML5标签的section
。
我以Firefox升级页面为基础。
https://www.mozilla.org/en-US/firefox/mobile/
截屏以查看我们已经完成的操作:
基本上,此HTML结构如下:
const PrivacySection = ({ ...props }) => {
console.log('-- privacy-section props: ', props);
return (
<section className="page-article-section feature-content" id="firefox-privacy">
<h3>Privacy</h3>
...
</section>
);
}
export default (
<article className="page-article" id="firefox">
<div className="features-scroller-section page-section" id="firefox-features">
<div className="features-scroller-container">
<header className="features-scroller-header">
<div className="features-scroller-header-container">
<h2 className="section-title">Firefox mobile</h2>
<a href="#mobile-download-buttons-firefox">Download now</a>
<nav className="features-scroller-nav">
<ul>
<li><a className="current" href="#firefox-sync">Sync</a></li>
<li><a href="#firefox-privacy">Privacy</a></li>
<li><a href="#firefox-extensions">Extensions</a></li>
</ul>
<button className="previous" type="button">Previous</button>
<button className="next" type="button">Next</button>
</nav>
</div>
</header>
<div className="features-scroller-content">
<section className="page-article-section feature-content" id="firefox-sync">
<h3>Sync</h3>
......
</section>
<ScrollControlls component={PrivacySection} />
<section className="page-article-section feature-content" id="firefox-extensions">
<h3>Extensions</h3>
...
</section>
</div>
</div>
</div>
</article>
);
我的ScrollControlls
组件如下:
import React, { Component } from "react";
export class ScrollControls extends Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
componentDidMount() {
document.querySelector('.page-article-section').addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
document.querySelector('.page-article-section').removeEventListener('scroll', this.handleScroll);
}
handleScroll = e => {
console.log('-- calling handle-scroll event: ', e);
}
render = () => {
const { component: Component } = this.props;
return <Component onScroll={this.handleScroll} />
}
}
export default ScrollControls;
问题是第二次滚动侦听器调用不起作用。 因此,请我需要帮助以适当地进行操作。