Drag拖拽 - 图1

Drag 拖拽

基本用法

  1. import { Drag, Button } from 'zarm';
  2. class Demo extends React.Component {
  3. currentX = 0;
  4. currentY = 0;
  5. state = {
  6. x: 0,
  7. y: 0,
  8. drag: false,
  9. };
  10. componentDidMount() {
  11. const { width, height } = this.box.getBoundingClientRect();
  12. const { width: containerWidth, height: containerHeight } = this.container.getBoundingClientRect();
  13. this.currentX = Math.round(Math.random() * (containerWidth - width));
  14. this.currentY = Math.round(Math.random() * (containerHeight - height));
  15. this.setState({
  16. x: this.currentX,
  17. y: this.currentY,
  18. });
  19. }
  20. onDragStart = (event, dragState) => {
  21. console.log('onDragStart', dragState);
  22. this.setState({
  23. drag: true,
  24. });
  25. }
  26. onDragMove = (event, dragState) => {
  27. console.log('onDragMove', dragState);
  28. const { width, height } = this.box.getBoundingClientRect();
  29. const { width: containerWidth, height: containerHeight } = this.container.getBoundingClientRect();
  30. let newX = this.currentX + dragState.offsetX;
  31. let newY = this.currentY + dragState.offsetY;
  32. if (newX < 0) {
  33. newX = 0;
  34. }
  35. if (newX > containerWidth - width) {
  36. newX = containerWidth - width;
  37. }
  38. if (newY < 0) {
  39. newY = 0;
  40. }
  41. if (newY > containerHeight - height) {
  42. newY = containerHeight - height;
  43. }
  44. this.setState({
  45. x: newX,
  46. y: newY,
  47. });
  48. return true;
  49. }
  50. onDragEnd = (event, dragState) => {
  51. console.log('onDragEnd', dragState);
  52. const { x, y } = this.state;
  53. this.currentX = x;
  54. this.currentY = y;
  55. this.setState({
  56. drag: false,
  57. });
  58. }
  59. render() {
  60. const { x, y, drag } = this.state;
  61. return (
  62. <div
  63. ref={(el) => { this.container = el; }}
  64. style={{
  65. height: 300,
  66. backgroundColor: '#ddd',
  67. position: 'relative'
  68. }}
  69. >
  70. <Drag
  71. onDragStart={this.onDragStart}
  72. onDragMove={this.onDragMove}
  73. onDragEnd={this.onDragEnd}
  74. >
  75. <div
  76. ref={(el) => { this.box = el; }}
  77. style={{
  78. display: 'inline-block',
  79. transform: `translate3d(${x}px, ${y}px, 0)`,
  80. }}
  81. >
  82. {
  83. drag
  84. ? <Button theme="danger">Let me go!</Button>
  85. : <Button theme="primary">Catch me~</Button>
  86. }
  87. </div>
  88. </Drag>
  89. </div>
  90. )
  91. }
  92. }
  93. ReactDOM.render(<Demo />, mountNode);

API

属性类型默认值说明
onDragStart(event?: MouseEvent | TouchEvent, dragState?: DragState) => void-触摸/点击 起始时触发的事件
onDragMove(event?: MouseEvent | TouchEvent, dragState?: DragState) => boolean-拖拽移动时触发的事件
onDragEnd(event?: MouseEvent | TouchEvent, dragState?: DragState) => void-触摸/点击 结束时触发的事件

DragState

属性类型默认值说明
startTimeDatenew Date()起始时间
startXnumber-起始点x坐标
startYnumber-起始点y坐标
offsetXnumber-横向偏移量
offsetYnumber-纵向偏移量