【发布时间】:2017-04-25 14:06:47
【问题描述】:
我有一个附加到组件中的窗口的滚动事件。我想控制台记录页面的滚动位置。但是,如果我快速移动滚动条,我只会在停止在 Chrome 中滚动时获得控制台日志。这是我的组件:
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
export class HeroImage extends Component {
constructor(props) {
super(props);
this.handleScroll = this.handleScrollAnimation.bind(this);
}
componentDidMount() {
window.addEventListener('scroll', this.handleScroll, false);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll, false);
}
handleScrollAnimation() {
// const heroImage = this.HeroImage;
console.log('here');
const doc = document.documentElement;
const scrollPosition = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
console.log(scrollPosition);
// heroImage.style.backgroundPosition = '50% 0';
// const animationCopy = this.AnimationCopy;
// if (this.isElementInViewport(animationTitle)) {
// animationTitle.classList.add('animated');
// }
// if (this.isElementInViewport(animationCopy)) {
// animationCopy.classList.add('animated');
// }
}
render() {
const styles = {
heroImage: {
backgroundImage: `url(${this.props.image})`
}
};
return (
<section className="hero-image">
<div
ref={c => {
this.HeroImage = c;
}}
style={styles.heroImage}
className="hero-image-bg"
/>
<div className="hero-image-content-container">
<div className="hero-image-content">
<div className="corners corners-top-left"/>
<div className="corners corners-bottom-left"/>
<div className="corners corners-top-right"/>
<div className="corners corners-bottom-right"/>
<h1>{this.props.title}</h1>
</div>
</div>
</section>
);
}
}
HeroImage.propTypes = {
title: PropTypes.string,
image: PropTypes.string
};
这是我在页面上调用组件的方式:
<HeroImage image={this.state.heroImage} title={this.state.title}/>
我在谷歌上搜索了很多,我找不到答案。我确定这只是一个小改动,但我需要将滚动事件移动到页面吗?这对我来说听起来不对。
【问题讨论】:
-
你能发布更多信息吗?我试图复制这个问题,但没有问题。这是工作代码:jsfiddle.net/vqrcs3px
-
我看到您的示例按我的预期工作。让我为您提供更多代码
-
我已经添加了整个组件代码以及如何将其添加到页面中以获取上下文
标签: javascript reactjs scroll dom-events