[英]React: Debounce for onKeyDown event
我在我的React Class組件中輸入了內容:
changeVal(event) {
console.log(event.keyKode)
}
...
return(
<input onKeyDown={event => this.changeVal(event)} />
)
如何在不使用lodash的情況下以500ms的去抖動在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)} />
)
但這根本不起作用。
嘗試
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)} />
)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.