2016-11-07 42 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

我希望每個人都像你的先生一樣閱讀快速和髒的代碼。 –