[英]How can I use debounce with initialValue in React-Final-Form?
我需要对输入onChange
使用debounce
,但我还需要表单的initialValues
中的值。 在使用value={props.value}
添加 debounce 时,键入时文本框中没有任何反应,因为props.value
在 debounce 计时器之后得到更新。 但是解决这个问题的方法是什么?
const debounced = debounce(e => {
input.onChange(e);
}, 500);
<FormControl
value={input.value}
onChange={e => {
e.persist();
debounced(e);
}}
/>
在上述情况下,输入框中没有输入任何内容。 如果我不传递value
prop,我不会在输入框中自动填充现有值。
希望获得有关如何实现这一目标的建议。
提前致谢!
下面应该去抖动输入并相应地更新 state。
const { useState } = React; const debounce = (callback, wait) => { let timeoutId = null; return (...args) => { window.clearTimeout(timeoutId); timeoutId = window.setTimeout(() => { callback.apply(null, args); }, wait); }; } const App = () => { const [current, setCurrent] = useState(''); const handleChange = debounce(e => setCurrent(e.target.value), 500); return ( <div> <form> <input type="text" onChange={handleChange} /> <p>{current}</p> </form> </div> ); }; ReactDOM.render(<App />, document.getElementById('react'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script> <div id="react"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.