反应:对 onKeyDown 事件进行去抖动



我的 React 类组件中有输入:

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

如何在没有 lodash 的情况下调用 keyDown 上的函数,并具有 500ms 的去抖动?

我尝试了接下来的事情:

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)} />
)

但这根本行不通。

尝试

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

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)} />
)
}
}

最新更新