首页 > 解决方案 > 反应:onKeyDown 事件的去抖动

问题描述

我在我的 React 类组件中有输入:

changeVal(event) {
  console.log(event.keyKode)
}
...

return(
   <input onKeyDown={event => this.changeVal(event)} />
)

如何在没有 lodash 的情况下以 500 毫秒的去抖动在 keyDown 上调用函数?

我尝试了下一件事:

debounce = (callback, delay) => {
    const timerClear = () => clear = true;
    var clear = true;
    return event => {
        if (clear) { 
            clear = false;
            setTimeout(timerClear, delay);
            callback(event);
        }
    }
}

return(
   <input onKeyDown={event => this.debounce(this.changeVal, 500)} />
)

但这根本不起作用。

标签: javascriptreactjsdebouncing

解决方案


尝试

const debounce = (func, wait = 500) => {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(this, args);
    }, wait);
  };
}

推荐阅读