- 在窗口的mousedown事件中保持MouseDown位置和滚动信息
- 在滚动条的鼠标按下事件中添加mousemove监听器
- 根据mousemove中的window.clientX和clientY计算scrollLeft和scrollTop
在窗口的onmouseup监听器中移除mousemove监听器。
class Application extends React.Component {
state = {isScrolling: false};
componentWillUpdate = (nextProps, nextState) =>{
if(this.state.isScrolling !== nextState.isScrolling ) {
this.toggleScrolling(nextState.isScrolling);
}
};
toggleScrolling = (isEnable) => {
if (isEnable) {
window.addEventListener('mousemove', this.onMouseMove);
window.addEventListener('mouseup', this.onMouseUp);
} else {
window.removeEventListener('mousemove', this.onMouseMove);
}
};
onScroll = (event) => {
};
onMouseMove = (event) => {
const {clientX, scrollLeft, scrollTop, clientY} = this.state;
this._scroller.scrollLeft = scrollLeft - clientX + event.clientX;
this._scroller.scrollTop = scrollTop - clientY + event.clientY;
};
onMouseUp = () => {
this.setState({isScrolling: false,
scrollLeft: 0, scrollTop: 0,
clientX: 0, clientY:0});
};
onMouseDown = (event) => {
const {scrollLeft, scrollTop} = this._scroller;
this.setState({isScrolling:true, scrollLeft, scrollTop, clientX:event.clientX, clientY:event.clientY});
};
attachScroller = (scroller) => {
this._scroller = React.findDOMNode(scroller);
};
render() {
return <div className='container'>
<div className="scroller"
ref={this.attachScroller}
onMouseDown={this.onScroll}
onScroll={this.onMouseMove}
>
<div className="child"/>
</div>
</div>;
}
}
React.render(<Application />, document.getElementById('app'));
有用的库
http://smikhalevski.github.io/react-scroll-box/
https://gist.github.com/gaearon/150fa1bed09c92abdb46
https://github.com/qiaolb/react-dragscroll