我對 react 很陌生,我使用 react 和 tailwinds css 創建了一個簡單的字典應用程式,我正在嘗試通過添加更多功能來改進它,我添加的功能之一是建議串列,以便用戶搜索對于一個詞,他們會得到一個相似詞的串列,但是,當我從搜索欄中清除該詞時,下拉選單仍然出現,見下圖
從搜索欄中清除單詞時,如何使其消失?另外,當單擊瀏覽器的任何位置時,如何使下拉選單消失?
我試著用我的代碼玩了將近一個小時,但不知道該怎么做,
在下面查看我的代碼
頁眉.js
``import { useContext, useState } from "react";
import { InputContext } from "../App";
import { getWordSuggestions } from "../api/getWordSuggestions";
import WordItem from "./WordItem";
const Header = () => {
const [value, setValue] = useState("");
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
const [searchSuggestions, setSearchSuggestions] = useState([]);
const { inputValue, setInputValue } = useContext(InputContext);
const handleSubmit = (word) => {
setInputValue(word);
setValue("");
setSearchSuggestions([]);
setIsDropdownOpen(false);
};
// On change of search field
const handleInputChange = async (e) => {
setValue(e.target.value);
const suggestions = await getWordSuggestions(e.target.value);
setSearchSuggestions(suggestions);
};
// To submit the form
const handleShowResult = (e) => {
e.preventDefault();
// if (!value) return;
handleSubmit(value);
};
return (
<div className="bg-gray-700">
<div className="container mx auto py-8">
<h1 className="text-3xl font-bold text-center text-white">
My Free Dictionary
</h1>
<p className="text-center mt-1 mb-10 text-white text-lg">
Find Definitions for word
</p>
<div className="flex itmes-center justify-center mt-5">
<form
className="LOOK relative flex border-2 border-gray-200 rounded"
onSubmit={handleShowResult}
>
<input
className="px-4 py-2 md:w-80"
type="text"
placeholder="Search.."
onChange={handleInputChange}
value={value}
onFocus={() => setIsDropdownOpen(true)}
/>
<button className="bg-blue-400 border-l px-4 py-2 text-white">
Search
</button>
{isDropdownOpen === true && (
<div className="word-suggestion-dropdown should-be-in-a-container absolute top-full bg-gray-50 w-full z-10">
{searchSuggestions.map((word) => {
return (
<WordItem
key={word}
word={word}
handleClick={handleSubmit}
/>
);
})}
</div>
)}
</form>
</div>
{inputValue && (
<h3 className="text-gray-50 text-center mt-4">
Results for:{" "}
<span className="text-white font-bold">{inputValue}</span>
</h3>
)}
</div>
</div>
);
};
export default Header;`
或者我的 git 倉庫
https://github.com/Moshe844/free-dictionary.git
uj5u.com熱心網友回復:
const handleInputChange = async (e) => {
if(!e.target.value){
setIsDropdownOpen(false);
}
setValue(e.target.value);
const suggestions = await getWordSuggestions(e.target.value);
setSearchSuggestions(suggestions);
};
在輸入發生變化時,我們將在 handleInputChange 函式中獲得值。如果值為空,我們可以將 isDropdownOpen 的狀態更新為 false。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/522593.html
