onClick works but onDoubleClick is ignored on React component

后端 未结 6 487
轻奢々
轻奢々 2020-12-05 03:38

I am building a Minesweeper game with React and want to perform a different action when a cell is single or double clicked. Currently, the onDoubleClick functi

6条回答
  •  自闭症患者
    2020-12-05 04:31

    Edit:

    I've found that this is not an issue with React 0.15.3.


    Original:

    For React 0.13.3, here are two solutions.

    1. ref callback

    Note, even in the case of double-click, the single-click handler will be called twice (once for each click).

    const ListItem = React.createClass({
    
      handleClick() {
        console.log('single click');
      },
    
      handleDoubleClick() {
        console.log('double click');
      },
    
      refCallback(item) {
        if (item) {
          item.getDOMNode().ondblclick = this.handleDoubleClick;
        }
      },
    
      render() {
        return (
          
    ); } }); module.exports = ListItem;

    2. lodash debounce

    I had another solution that used lodash, but I abandoned it because of the complexity. The benefit of this was that "click" was only called once, and not at all in the case of "double-click".

    import _ from 'lodash'
    
    const ListItem = React.createClass({
    
      handleClick(e) {
        if (!this._delayedClick) {
          this._delayedClick = _.debounce(this.doClick, 500);
        }
        if (this.clickedOnce) {
          this._delayedClick.cancel();
          this.clickedOnce = false;
          console.log('double click');
        } else {
          this._delayedClick(e);
          this.clickedOnce = true;
        }
      },
    
      doClick(e) {
        this.clickedOnce = undefined;
        console.log('single click');
      },
    
      render() {
        return (
          
    ); } }); module.exports = ListItem;

    on the soapbox

    I appreciate the idea that double-click isn't something easily detected, but for better or worse it IS a paradigm that exists and one that users understand because of its prevalence in operating systems. Furthermore, it's a paradigm that modern browsers still support. Until such time that it is removed from the DOM specifications, my opinion is that React should support a functioning onDoubleClick prop alongside onClick. It's unfortunate that it seems they do not.

提交回复
热议问题