我正在尝试使用 React 创建滑动事件。我不想使用任何外部组件或 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 组件中,我正在尝试做类似的事情:
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
它可以工作,但是我怎样才能制作滑动效果?
这里是 jsfiddle .
最佳答案
您可以将 onTouch
事件处理程序添加到您的 React 组件:
onTouchStart={touchStartEvent => this.handleTouchStart(touchStartEvent)}
onTouchMove={touchMoveEvent => this.handleTouchMove(touchMoveEvent)}
onTouchEnd={() => this.handleTouchEnd()}
您可能还想为鼠标事件添加事件处理程序以实现跨平台兼容性:
onMouseDown={mouseDownEvent => this.handleMouseDown(mouseDownEvent)}
onMouseMove={mouseMoveEvent => this.handleMouseMove(mouseMoveEvent)}
onMouseUp={() => this.handleMouseUp()}
onMouseLeave={() => this.handleMouseLeave()}
在事件处理程序中更新状态的 left
属性的想法是正确的,但是如果您希望滑动功能感觉自然,则需要跟踪指针的位置(是它是鼠标或触摸)通过使用事件的 clientX
属性更新 left
。
为此,您需要存储第一次触摸的位置并将 left
设置为等于触摸位置的变化。为了增加真实感,您还可以跟踪触摸的速度并在触摸完成后继续为组件设置动画。
这是我制作的一个快捷的代码笔,用于滑动以从列表中删除项目:
关于javascript - React js中的滑动效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40463173/