[英]How can I use debounce with initialValue in React-Final-Form?
I need to use debounce
on input onChange
, but I also need the value from the form's initialValues
.我需要对输入
onChange
使用debounce
,但我还需要表单的initialValues
中的值。 On adding debounce with value={props.value}
nothing happens in the textbox on typing which is expected as props.value
get updated after the debounce timer.在使用
value={props.value}
添加 debounce 时,键入时文本框中没有任何反应,因为props.value
在 debounce 计时器之后得到更新。 But what is the solution for this?但是解决这个问题的方法是什么?
const debounced = debounce(e => {
input.onChange(e);
}, 500);
<FormControl
value={input.value}
onChange={e => {
e.persist();
debounced(e);
}}
/>
In the above case, nothing gets typed in the input box.在上述情况下,输入框中没有输入任何内容。 And if I don't pass
value
prop, I don't get my existing value auto-populated in the input box.如果我不传递
value
prop,我不会在输入框中自动填充现有值。
Would love to get suggestions on how to achieve this.希望获得有关如何实现这一目标的建议。
Thanks in advance!提前致谢!
The following should debounce the input and update the state accordingly.下面应该去抖动输入并相应地更新 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.