我创建了一个允许拖放功能的组件。我现在遇到的问题是,我不知道如何在鼠标向上滚动时增加动量(而且这对反弹效果并不重要)。 重要的部分是:如何在一段时间内更新组件(取决于拖动的强度)?
下面是我的滚动组件代码:
class DraggingScrollView extends React.Component {
constructor(props) {
super(props);
this.state = {
isScrolling: false,
scrollLeft: 0,
clientX: 0,
};
this.scrollContainer = React.createRef();
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
this.handleScroll = this.handleScroll.bind(this);
}
componentWillUpdate(nextProps, nextState) {
const { isScrolling } = this.state;
if (isScrolling !== nextState.isScrolling) {
this.setScrollingEnabled(nextState.isScrolling);
}
}
setScrollingEnabled(isEnabled) {
if (isEnabled) {
window.addEventListener('mousemove', this.handleScroll);
} else {
window.removeEventListener('mousemove', this.handleScroll);
}
}
handleMouseDown(event) {
const { clientX } = event;
const { scrollLeft } = this.scrollContainer.current;
this.setState({
isScrolling: true,
scrollLeft,
clientX,
});
}
handleMouseUp() {
this.setState({
isScrolling: false,
scrollLeft: 0,
clientX: 0,
});
}
handleScroll(event) {
const { scrollLeft, clientX } = this.state;
const scrollContainer = this.scrollContainer.current;
const scrollDestination = scrollLeft + clientX - event.clientX;
scrollContainer.scrollLeft = scrollDestination;
}
render() {
const { children, scrollContainerHeight } = this.props;
return (
<div
id="scrollContainer"
ref={this.scrollContainer}
role="presentation"
style={{ paddingTop: scrollContainerHeight }}
onMouseDown={this.handleMouseDown}
onMouseUp={this.handleMouseUp}
>
<div id="scrollContentContainer">{children}</div>
</div>
);
}
}