import React,{useState} from 'react';
const app = () =>{
const [inputValue,setInputValue] = useState();
const handleChange = (e)=>{
setInputValue(e.target.value);
console.log(inputValue);
}
const debounce =function (fn , d) {
let timer;
return function(){
let context = this,
args=arguments;
clearTimeout(timer);
timer = setTimeout(() =>{
fn.apply(context,args)
},d)
}
}
const betterFunction = debounce(handleChange, 300);
return (
<>
<input type='text' value={inputValue} onChange={betterFunction}/>
<div>{inputValue}</div>
</>
)
}
export default app;
在上面的代码中,一旦在
inputfield
中输入任何内容,我就无法进行任何更改。基本上更新inputfield
卡住了。请帮忙推理并提前感谢您。
或者你可以使用 useDebounce
包的
ahooks
钩子。
import { useState } from 'react';
import { useDebounce } from 'ahooks';
function App() {
const [inputValue, setInputValue] = useState<string>();
const debouncedValue = useDebounce(inputValue, { wait: 500 });
return (
<>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<div>{debouncedValue}</div>
</>
);
}
export default App;