- 維護的MouseDown位置和滾動信息onmousedown事件窗口的
- 添加鼠標移動監聽器上滾動的鼠標按下
- 計算scrollLeft和scrollTop的根據對窗口的onmouseup監聽器窗口clientX和clientY在鼠標移動
刪除鼠標移動。
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>;
}
}
/*
* Render the above component into the div#app
*/
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