|
| 1 | +/** |
| 2 | + * Created by joe on 16/9/2. |
| 3 | + */ |
| 4 | + |
| 5 | +import React from "react"; |
| 6 | +import _ from "lodash"; |
| 7 | + |
| 8 | +export default class DragScroll extends React.Component { |
| 9 | + constructor(props) { |
| 10 | + super(props); |
| 11 | + this.state = { |
| 12 | + data: props.dataSource, |
| 13 | + dragging: false |
| 14 | + }; |
| 15 | + } |
| 16 | + |
| 17 | + render() { |
| 18 | + return <div style={{height: this.props.height, width: this.props.width, overflow: 'auto'}} |
| 19 | + onMouseUp={this.mouseUpHandle.bind(this)} |
| 20 | + onMouseMove={this.mouseMoveHandle.bind(this)} |
| 21 | + ref="container"> |
| 22 | + {this.renderChildren(this.props.children)} |
| 23 | + </div>; |
| 24 | + } |
| 25 | + |
| 26 | + componentDidMount() { |
| 27 | + window.addEventListener('mouseup', this.mouseUpHandle.bind(this)); |
| 28 | + window.addEventListener('mousemove', this.mouseMoveHandle.bind(this)); |
| 29 | + } |
| 30 | + |
| 31 | + componentWillUnmount() { |
| 32 | + window.removeEventListener('mouseup', this.mouseUpHandle.bind(this)); |
| 33 | + window.removeEventListener('mousemove', this.mouseMoveHandle.bind(this)); |
| 34 | + } |
| 35 | + |
| 36 | + mouseUpHandle(e) { |
| 37 | + if (this.state.dragging) { |
| 38 | + this.state.dragging = false; |
| 39 | + this.setState(this.state); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + mouseDownHandle(e) { |
| 44 | + if (!this.state.dragging) { |
| 45 | + this.state.dragging = true; |
| 46 | + this.setState(this.state); |
| 47 | + this.lastClientX = e.clientX; |
| 48 | + this.lastClientY = e.clientY; |
| 49 | + e.preventDefault(); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + mouseMoveHandle(e) { |
| 54 | + if (this.state.dragging) { |
| 55 | + console.log(this.refs.container.scrollTop); |
| 56 | + this.refs.container.scrollLeft -= |
| 57 | + (-this.lastClientX + (this.lastClientX = e.clientX)); |
| 58 | + this.refs.container.scrollTop -= |
| 59 | + (-this.lastClientY + (this.lastClientY = e.clientY)); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + mouseLeaveHandle(e) { |
| 64 | + // if (this.state.dragging) { |
| 65 | + // this.state.dragging = false; |
| 66 | + // this.setState(this.state); |
| 67 | + // } |
| 68 | + } |
| 69 | + |
| 70 | + |
| 71 | + renderChildren(dom, type) { |
| 72 | + if (_.isArray(dom)) { |
| 73 | + return dom.map((item, index) => { |
| 74 | + return React.cloneElement(item, { |
| 75 | + key: item.key || index, |
| 76 | + onMouseUp: this.mouseUpHandle.bind(this), |
| 77 | + onMouseDown: this.mouseDownHandle.bind(this) |
| 78 | + }); |
| 79 | + }); |
| 80 | + } else if (_.isObject(dom)) { |
| 81 | + return React.cloneElement(dom, { |
| 82 | + key: item.key || index, |
| 83 | + onMouseUp: this.mouseUpHandle.bind(this), |
| 84 | + onMouseDown: this.mouseDownHandle.bind(this) |
| 85 | + }); |
| 86 | + } |
| 87 | + } |
| 88 | +} |
0 commit comments