簡體   English   中英

如何在 React-Final-Form 中使用 debounce 和 initialValue?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM