【问题标题】:React: Debounce for onKeyDown event反应:onKeyDown 事件的去抖动
【发布时间】:2019-12-21 22:05:13
【问题描述】:

我在我的 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)} />
)

但这根本行不通。

【问题讨论】:

标签: javascript reactjs debouncing


【解决方案1】:

debounce 函数的返回值应直接用作处理程序。在此处查看示例:https://codesandbox.io/s/musing-dust-iy7tq

class App extends React.Component {
  changeVal(event) {
    console.log(event.keyCode)
  }

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

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

【讨论】:

    【解决方案2】:

    试试

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-08
      • 1970-01-01
      • 2016-07-24
      相关资源
      最近更新 更多