Jame's Blog

前端開發心得 front-end Develop

如何在 react-slick 避免 Swipe 的時候觸發到連結事件

| Comments

有網友遇到一個問題,在使用react-slick的時候,若其中的 slider 裡面有 a 標籤的時候,
當使用滑鼠,或觸控點擊的時候,會觸發到link的事件。
為了避免發生,就必須針對該事件的狀況做偵測。

本範例的範例內容是從下面這兩個範例參考而來的

實作方式:

  1. 先把測試環境先實做出來。
  2. 然後再根據實際狀況測試。
  3. 實際的操作react 的 event 行為
  4. 再根據實際的狀況做判斷

完成內容如下:
https://esnextb.in/?gist=fd8d61ddcd934623ee4a3872c113d63f

{
  "name": "react-slick-swipe-preventDefault",
  "version": "0.14.8",
  "dependencies": {
    "react": "15.4.2",
    "react-dom": "15.4.2",
    "react-slick": "0.14.8"
  }
}
import React from 'react';
import ReactDOM from 'react-dom';
import Slider from 'react-slick';

var ReactSlickDemo = React.createClass({
  getInitialState: function() {
        return {
            moving: false,
            clicking:false
        };
  },
  handleClick: function (e) {
    if(this.state.moving){
      console.log("preventDefault");
      e.preventDefault();
      this.state.clicking = false;
      this.state.moving = false;
    }
    this.displayState("handleClick");
  },
  displayState: function(title){
     console.log(title,this.state.clicking,this.state.moving);
  },
  mouseMove: function(e){
    if(this.state.clicking){
      this.state.moving = true;
    }else{
      this.state.moving = false;
    }
    this.displayState("mouseMove");
  },
  ontouchstart: function(e){
    this.state.clicking = true;
    this.displayState("ontouchstart");
  },
  touchMove: function(e){
    this.state.moving = true;
    this.displayState("touchMove");
  },
  touchCancel: function(e){
    this.state.clicking = false;
    this.displayState("onTouchCancel");
  },
  touchEnd: function(e){
    this.state.clicking = false;
    this.displayState("touchEnd");
  },
  onmouseup: function(e){
    this.state.clicking = false;
    this.displayState("onmouseup");
  },
  onmousedown: function(e){
    this.state.clicking = true;
    this.displayState("onmousedown");
  },
  render: function() {
    var settings = {
        dots: true,
        centerMode:true
    }
    
    var linkscount = 4;
    var items = [];
    for(i=0;i<linkscount;i++){
      items.push(<div key={i} >
      <a draggable="false" 
      onTouchStart={this.ontouchstart} 
      onMouseDown={this.onmousedown}
      onMouseUp={this.onmouseup}
      onMouseMove={this.mouseMove} 
      onTouchEnd={this.touchEnd} 
      onTouchCancel={this.touchCancel} 
      onTouchMove={this.touchMove} 
      onClick={this.handleClick} 
      href="#" 
      target="_blank"><img draggable="false" src='http://placekitten.com/g/400/200' /></a></div>);
    }
        
    return (
        <div className='container'>
        <Slider {...settings}>
         { items }
        </Slider>
      </div>
    );
  }
});

ReactDOM.render(
  <ReactSlickDemo />,
  document.getElementById('container')
);

參考資料: SyntheticEvent

Comments

comments powered by Disqus