Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React 中单击和双击事件冲突的解决 #45

Open
shuangmianxiaoQ opened this issue Jul 8, 2019 · 0 comments
Open

React 中单击和双击事件冲突的解决 #45

shuangmianxiaoQ opened this issue Jul 8, 2019 · 0 comments
Labels
React 系列 React使用及采坑小集 工作相关 记录工作中遇到的问题或收获

Comments

@shuangmianxiaoQ
Copy link
Owner

shuangmianxiaoQ commented Jul 8, 2019

在业务需求中遇到这样的场景,对一个元素同时添加单击和双击事件,发现两个事件会有冲突,导致无法区分单击和双击事件,下面提供两种解决方案:

  1. 通过设置延时来实现
let count = 0;

class App extends Component {
  handleClick = () => {
    count++;

    setTimeout(() => {
      if (count === 1) {
        // 单击事件处理
      } else if (count === 2) {
        // 双击事件处理
      }

      count = 0;
    }, 300);
  }

  render() {
    return (
      <div onClick={this.handleClick} />
    )
  }
}
  1. 借助防抖函数实现
let clickTasks = []; // Array of debounced click events

class App extends Component {
  handleClick = () => {
    const task = _.debounce(() => {
      // 单击事件处理
      clickTasks = [];
    }, 300);
    clickTasks.push(task);
    task();
  }

  handleDoubleClick = () => {
    if(clickTasks.length > 0) {
      _.map(clickTasks, task => task.cancel());
    }
  // 双击事件处理
  }

  render() {
    return (
      <div onClick={this.handleClick} onDoubleClick={this.handleDoubleClick} />
    )
  }
}
@shuangmianxiaoQ shuangmianxiaoQ added 工作相关 记录工作中遇到的问题或收获 React 系列 React使用及采坑小集 labels Jul 8, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
React 系列 React使用及采坑小集 工作相关 记录工作中遇到的问题或收获
Projects
None yet
Development

No branches or pull requests

1 participant