2016-11-07 41 views
3

我正尝试使用React创建滑动事件。我不想使用任何外部组件或jQuery。反应js中的滑动效果

的CSS是这样的:

.outter{ 
    position:relative; 
    width: 100%; 
    height: 150px; 
    background-color: blue; 
} 

.inner{ 
    position: absolute; 
    width: 1000%; 
    left: 50px; 
} 
.child{ 
    float: left; 
    margin-right: 15px; 
} 

在反应成分,我试图做一些事情,如:

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

+0

如果你真的想自己做,那么你需要倾听和处理鼠标按下+鼠标移动+鼠标事件。 – dfsq

回答

6

您可以添加onTouch事件处理程序到你的反应的组分:

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属性的想法,但是如果您希望滑动功能感觉自然,则需要通过更新left来跟踪指针的位置(无论是鼠标还是触摸)使用事件的clientX属性。

为此,您需要存储第一次触摸的位置并将left设置为等于触摸位置的变化。为了增加真实感,您还可以跟踪触摸的速度并在触摸完成后继续对组件进行动画处理。

这里有一个快速正脏codepen我的刷卡从列表中删除的项进行:

https://codepen.io/swingthing/pen/ZBGBJb/

+0

只需注意:'onTouchStart = {touchStartEvent => this.handleTouchStart(touchStartEvent)}'在功能上等同于'onTouchStart = {this.handleTouchStart}',但效率稍低,因为它会导致每次定义一个新的匿名函数渲染。 – chadoh

+0

很好的答案和codepen。奇怪的是,在复制你的时候,我最终会遇到更多的经验。 – chadoh

+0

我希望每个人都像你的先生一样阅读快速和脏的代码。 –