簡體   English   中英

使用 HTMLFormElement.reset() 和 Downshift 和 react-hook-form

[英]Using HTMLFormElement.reset() with Downshift and react-hook-form

我正在使用 DownshiftJS 使用useCombobox掛鈎創建自動完成組件。 一切順利,並使用react-hook-form進行測試。 不幸的是,我遇到了一個問題,即react-hook-form可用的 reset 函數會觸發HTMLFormElement.reset()方法,但不會觸發 Downshift 組件內的任何狀態/輸入更改。

這意味着當用戶從列表中選擇一個項目(觸發Autocomplete一個事件),點擊重置按鈕,然后再次點擊輸入時,列表將被過濾到之前選擇的項目。 這是因為所選項目存儲在selectedItem內部狀態中。

如何獲得重置方法以觸發Autocomplete組件內的更改並清除selectedItem狀態?

我在這里隔離了這個問題。

您可以使用React.useEffect來檢測用戶是否點擊了重置按鈕並在您的Autocomplete組件中相應地重置所選項目

const [inputItems, setInputItems] = useState(options);
const {
  inputValue,
  ...
} = useCombobox({
  items: inputItems,
  ...
});

React.useEffect(() => {
  if (!inputValue) {
    // user resets value. Reset selected option
    setInputItems(options);
  }
}, [inputValue, options, setInputItems]);

現場演示

編輯 64144984/using-htmlformelement-reset-with-downshift-and-react-hook-form

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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