具有3个组件,分别覆盖车身的整个宽度和指定的高度。我需要在滚动方向上滚动到上一个/下一个组件。我正在使用react建议的onWheel事件,并且在滚动和检测方向时一切正常。 当一个人向上/向下滚动并且出现错误的组件(第一个)时,就会出现问题。
这是我的代码
import React, { Component } from "react";
class App extends Component {
state = {
refObject: {
1: React.createRef(),
2: React.createRef(),
3: React.createRef()
},
lastRefId: 0,
scrollUp: true
};
handleScroll = (event, caller) => {
let directionUp = event.deltaY < 0 ? true : false;
if (caller !== this.state.lastRefId || this.state.scrollUp !== directionUp) {
if (directionUp) {
this.setState({ scrollUp: true });
if (caller > 1) {
window.scrollTo({
top: this.state.refObject[caller - 1],
behavior: "smooth"
});
}
} else {
this.setState({ scrollUp: false });
if (caller < 3) { // since I have 3 components
window.scrollTo({
top: this.state.refObject[caller + 1],
behavior: "smooth"
});
}
}
}
this.setState({ lastRefId: caller, scrollUp: directionUp });
};
render() {
return (
<React.Fragment>
<Component1
key={1}
refProp={this.state.refObject[1]}
onWheel={event => this.handleScroll(event, 1)}
/>
<Component2
key={2}
refProp={this.state.refObject[2]}
onWheel={event => this.handleScroll(event, 2)}
/>
<Component3
key={3}
refProp={this.state.refObject[3]}
onWheel={event => this.handleScroll(event, 3)}
/>
</React.Fragment>
);
}
}
export default App;
我的组件(1-3)如下:
class Component1 extends Component {
state = {};
render() {
return (
<React.Fragment>
<div
ref={this.props.refProp}
className="d-flex flex-row mt-0 text-center p-3"
onWheel={this.props.onWheel}>
This is a Component
</div>
</React.Fragment>
);
}
}
例如,当我向下滚动覆盖整个身体宽度的第二个组件时,它将向上滚动到第一个组件。
感谢您的帮助
答案 0 :(得分:0)
scrollTo方法中缺少的是当前对象,并引用了offsetTop属性。最好在enter link description here中由@Kokovin提及。 因此,我的手柄滚动应该像这样:
handleScroll = (event, caller) => {
let directionUp = event.deltaY < 0 ? true : false;
if (caller !== this.state.lastRefId || this.state.scrollUp !== directionUp) {
if (directionUp) {
this.setState({ scrollUp: true });
if (caller > 1) {
window.scrollTo({
top: this.state.refObject[caller - 1],
behavior: "smooth"
});
}
} else {
this.setState({ scrollUp: false });
if (caller < 3) { // since I have 3 components
window.scrollTo({
top: this.state.refObject[caller + 1],
behavior: "smooth"
});
}
}
}
this.setState({ lastRefId: caller, scrollUp: directionUp });
};