我在我的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)} />
)
但这根本不起作用。
答案 0 :(得分:0)
尝试
/dashboard
答案 1 :(得分:0)
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)} />
)
}
}