You can add onTouch
event handlers to your React components:
onTouchStart={touchStartEvent => this.handleTouchStart(touchStartEvent)}
onTouchMove={touchMoveEvent => this.handleTouchMove(touchMoveEvent)}
onTouchEnd={() => this.handleTouchEnd()}
You may also want to add event handlers for mouse events for cross-platform compatibility:
onMouseDown={mouseDownEvent => this.handleMouseDown(mouseDownEvent)}
onMouseMove={mouseMoveEvent => this.handleMouseMove(mouseMoveEvent)}
onMouseUp={() => this.handleMouseUp()}
onMouseLeave={() => this.handleMouseLeave()}
You have the right idea for updating the left
property of state in an event handler, but if you want the swiping functionality to feel natural you'll need to track the position of the pointer (be it a mouse or a touch) by updating left
using the event's clientX
property.
To do this, you'll need to store the position of the first touch and set left
equal to the change in the touch's location. For added realism, you can also keep track of the touch's velocity and continue animating the component after the touch is finished.
Here's a quick-n-dirty Codepen I made for swiping to remove items from a list:
https://codepen.io/swingthing/pen/ZBGBJb/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…