[英](React, JS, TS) the function works "onClick" but not on "KeyPress"
我有一個函數在調用“onClick”時按預期工作,但在使用“onKeyPress”調用時省略了 if 語句。
語境
想象一個輸入,您可以在其中搜索食物食譜(例如“披薩”),然后您從帶有食譜的 API 中獲取食譜列表。
所有相關代碼解釋
↓ 此變量存儲一個布爾值。 檢查來自輸入的查詢是否包含在當前顯示的配方列表的任何標題中。
const recipeListHasQuery = recipectx.data.map((recipe: any) => {
return recipe.title.toLowerCase().includes(query);
})
如果列表中至少有一個食譜標題不包括我們正在搜索的查詢,我們可以清除列表。
(基本上,如果您搜索“pizza”,現在搜索“burger”並且披薩食譜的任何標題中都沒有“burger”,我們可以清除列表並顯示漢堡食譜)
↓ 這個函數在調用“onClick”時有效,在“onKeyPress”上無效。
const clearView = () => {
console.log('i log on enter')
↓ does not work on enter
if (!recipeListHasQuery.includes(true)) {
const recipeList = document.querySelector(".recipe__list") as HTMLElement;
recipeList!.innerHTML = "";
}
↓ 此函數在調用“onKeyPress”時有效,但省略了 if 語句
const HandleInputOnKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === "Enter") {
HandleInputChange(event as any); ← this works fine on "Enter"
// clearView(); ← works on "Enter" but omits the if statement
↓ just typing it out does not work either
if (!recipeListHasQuery.includes(true)) {
const recipeList = document.querySelector(".recipe__list") as HTMLElement;
recipeList!.innerHTML = "";
}
}
};
所以問題是,每個查詢都沒有一個食譜列表,而是添加一個新的
↓ 這是我調用函數的方式。
<form>
<input onKeyPress={HandleInputOnKeyPress}></input>
<button onClick={clearView}>
Search
</button>
</form>
該函數被正確調用,因此這與單擊和按鍵事件無關。 問題出在邏輯上,特別是在 clearView 函數中的 if 語句中。 您可以在 if 之前 console.log(recipeListHasQuery.includes(true)) 並從那里調試邏輯
如果您對此有困難,請隨時將您的代碼添加到 jsfiddle,我將幫助您調試它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.