在React Leaflet中捕捉多边形(圆形)的双击事件

3

我可以捕获单击事件

<Circle onClick={ (event) => this.seatClickHandler(event, seat) } ... />

我想捕获双击事件,这在react-leaflet中可能吗?

我已经禁用了双击地图放大的功能,因此如果有关于地图的事件,那么对于多边形肯定也会有可用的事件吧?


1
使用rxjs有一个相当简单的解决方案,但我不知道你是否想使用rxjs? - Daniel Hoppe Alvarez
3个回答

2

我不得不绕过一些DOM的限制。

我曾经检查某个元素在短时间内是否被点击了两次。

/**
 * Number of clicks.
 * 
 * @type {Number}
 */
let seatClickNumber;

/**
 * Id of element
 * 
 * @type {Number}
 */
let clickedSeatId;

/**
 * Last timeout ID
 * 
 * @type {Number}
 */
let timeoutId;

/**
 * Checks if seat is double clicked.
 * 
 * @param {Object} seat
 * 
 * @returns {boolean}
 */
isDoubleClick = (seat) => {
   if (clickedSeatId === seat['seatLabelId']) {
        seatClickNumber = seatClickNumber + 1;
    }

    clickedSeatId = seat['seatLabelId'];

    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
        clickedSeatId = '';
        seatClickNumber = 1;
    }, 600);

    return seatClickNumber > 1;
};

/**
 * Selects one seat by click event or multiple by holding ctrl key whn clicking.
 *
 * @param {Object} event
 * @param {Object} seat
 */
seatClickHandler = (event, seat) =>
{
    if(this.isDoubleClick(seat)) {
        alert('Double Click!!!');
    }

    let index = this.props.selectedSeats.indexOf(seat);

    if (index !== -1) {
        this.props.deselectSeat(seat);
    } else {
        event.originalEvent.ctrlKey ? this.props.addSelectedSeats(seat) : this.props.setSelectedSeats(seat);
    }
};

1

基于RxJS的解决方案,可以在构造函数或初始化函数中使用:

const clickEvents = Rx.Observable.fromEvent(document.getElementById('yourId'), 'click');

const unsubscribe$= Rx.Subject()


clickEvents
  .buffer(clickEvents.debounce(300))
  .map(list => list.length)
  .filter(x => x === 2)
  .takeUntil(unsubscribe$)
  .subscribe(() => {
      console.log('you can handle the double click here');
  })

每当您想要取消对事件的订阅时,

您调用一个使用

 unsubscribe$.next()
 unsubscribe$.complete()

我正在使用React,但在项目中使用其他库的选项不多:/ - Stevan Tosic
我也找到了一些不需要导入外部库的解决方案,如果你想的话可以查看我的答案。 - Stevan Tosic

0
不要在同一元素上注册单击和双击事件:无法区分单击事件和导致双击事件的单击事件。
这不是React的限制,而是DOM的单击和双击事件的限制。正如Quirksmode的click documentation:所建议的那样。

我不得不绕个弯,你可以检查一下我的解决方案。 - Stevan Tosic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接