在React JS中滑动效果 [英] Swipe effect in react js
问题描述
我正在尝试使用React创建滑动事件.我不想使用任何外部组件或jquery.
I'm trying to create a swipe event using React. I do not want to use any external component or jquery.
css类似于:
.outter{
position:relative;
width: 100%;
height: 150px;
background-color: blue;
}
.inner{
position: absolute;
width: 1000%;
left: 50px;
}
.child{
float: left;
margin-right: 15px;
}
在react组件中,我正在尝试做类似的事情:
In the react component I'm trying to do something like :
class Test extends React.Component {
constructor(props){
super(props);
this.state = {
left: 0
}
}
handleSwipe(){
this.setState({left: -350})
}
render(){
return(
<div className="outter">
<div className="inner" style={{left: this.state.left}} onSwipe={this.handleSwipe.bind(this)}>
<div className="child"><img src="http://placehold.it/350x150" /></div>
<div className="child"><img src="http://placehold.it/350x150" /></div>
<div className="child"><img src="http://placehold.it/350x150" /></div>
<div className="child"><img src="http://placehold.it/350x150" /></div>
</div>
</div>
)
}
}
React.render(<Test />, document.getElementById('container'));
如何识别滑动事件?
如果在我的示例中代替 onSwipe
添加 onClick
,它可以工作,但是如何制作滑动效果?
If I in my example instead of onSwipe
add onClick
it works, but how can I make the swipe effect?
这里是 jsfiddle .
推荐答案
您可以在您的React组件中添加 onTouch
事件处理程序:
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()}
在事件处理程序中更新state的状态的 left
属性是正确的主意,但是如果您希望滑动功能感觉自然,则需要跟踪指针的位置((鼠标或触摸)),方法是使用事件的 clientX
属性更新 left
.
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.
为此,您需要存储第一次触摸的位置,并将 left
设置为等于触摸位置的变化.为了增加真实感,您还可以跟踪触摸的速度,并在触摸完成后继续为组件设置动画.
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.
这是我制作的快速n肮脏的Codepen,用于从列表中删除项目:
Here's a quick-n-dirty Codepen I made for swiping to remove items from a list:
https://codepen.io/swingthing/pen/ZBGBJb/
这篇关于在React JS中滑动效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!