我有一个附加到组件中窗口的滚动事件。我想控制台记录页面的滚动位置。但是,如果我快速移动滚动条,当我停止在 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}/>
我已经用谷歌搜索了很多,但找不到答案。我确定这只是一个小更改,但是我需要将滚动事件移动到页面吗?这对我来说听起来不对。
最佳答案
我只是根据我在工作项目中所做的事情将这个示例放在一起。在此代码片段中,滚动事件会在您滚动时触发,而不仅仅是在完成后触发。
import React, { Component } from 'react';
import './App.css';
import {findDOMNode} from 'react-dom';
class App extends Component {
constructor() {
super();
this.state = {
stuff: []
}
this.handleScroll = this.handleScroll.bind(this);
}
componentDidMount() {
let stuff = this.state.stuff;
for(let i = 0; i < 250; i++) {
stuff.push(i);
}
this.setState({stuff});
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll() {
let node = findDOMNode(this);
let dimensions = node.getBoundingClientRect();
console.log(dimensions);
}
createRow(s, i) {
return (
<h1 key={i}>Foo</h1>
)
}
render() {
return (
<div className="App">
{this.state.stuff.map((s, i) => this.createRow(s, i))}
</div>
);
}
}
export default App;
我不完全确定我是否理解你的代码和我的代码之间的区别,但这应该对你有用。
关于javascript - 在 Chrome 中的窗口上停止滚动之前,滚动事件不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43612994/