React-Bootstrap-Typeahead:清除菜单选择

React-Bootstrap-Typeahead: Clear on Menu Selection

在我的 React-Bootstrap-Typeahead 中,我需要立即在输入中设置一个状态变量和 clear 以允许新的搜索。现在发生的事情是:

  1. 已提供建议列表
  2. 当我select一个菜单项时,我的handleChange被正确执行
  3. select离子显示在文本字段中。

我需要设置 var clickedSelection 并重置新搜索的输入。一切都应该清理和关闭。 (注意:我使用的是 React-Bootstrap-TypeaheadAsyncTypeahead 变体。)

const [isLoading, setIsLoading] = useState(false);
const [searchResults, setSearchResults] = useState([]);
const [clickedSelection, setClickedSelection] = useState({});

// Fetch Function
const fetchResults = async (token) => {
   setIsLoading(true);
   const response = await axios.get('/myurl/search/' + token); // Axios for Data Fetch
   setSearchResults(response.data); // Set results state var
}

// Handle onChange Function: set 'clickedSelection'
const handleChange = (options) => {
   console.log(JSON.stringify(options[0]);
   setClickedSelection(options[0]);
}

<AsyncTypeahead
    isLoading={isLoading}
    onSearch={(query) => {
       fetchResults(query)
    }}
    option={searchResults}
    labelKey={option => `${option.firstName ${option.lastName}`}
    onChange={handleChange}
/>

您可以在 typeahead 上设置 ref 并使用 the public clear method 清除 onChange 处理程序中的选择:

const typeaheadRef = useRef(null);

const handleChange = (selected) => {
  setClickedSelection(selected[0]);
  typeaheadRef.current.clear();
};

return (
  <AsyncTypeahead
    ...
    onChange={handleChange}
    ref={typeaheadRef}
  />
);

工作沙箱:https://codesandbox.io/s/purple-flower-0t5m8