當您按下帶有有限文本的搜索按鈕時,沒有任何反應。單擊搜索時需要它,以便它顯示一個錯誤的視窗
const SearchForm = () => {
const [isSearchOpen, setSearchOpen] = useState(false),
formRef = useRef(null);
useClickOutside(formRef, () => setSearchOpen(false));
const [inputText, setInputText] = useState("");
const handleSubmit = e => {
if (inputText.length >= 150 ) {
e.preventDefault();
}
};
return (
<form
ref={formRef}
className={cn("search-form", {
"search-form--focus": isSearchOpen,
})}
onClick={() => setSearchOpen(true)}
onKeyPress={() => setSearchOpen(true)}
action="/search"
// eslint-disable-next-line
role="searchbox"
onSubmit={handleSubmit}
>
<input
value={inputText}
onChange={e => setInputText(e.target.value)}
className="search-form__input"
name="filter"
type="text"
/>
<button
className="search-form__button"
type="submit"
aria-label="Header search button"
/>
</form>
);
};
uj5u.com熱心網友回復:
一個非常簡單的解決方案是在輸入框附近顯示一條警告訊息并在您的提交功能中對其進行驗證
const SearchForm = () => {
const [isSearchOpen, setSearchOpen] = useState(false),
formRef = useRef(null);
useClickOutside(formRef, () => setSearchOpen(false));
const [inputText, setInputText] = useState("");
const handleSubmit = e => {
e.preventDefault();
if(inputText.length <= 150) {
//submit
}
};
return (
<form
ref={formRef}
className={cn("search-form", {
"search-form--focus": isSearchOpen,
})}
onClick={() => setSearchOpen(true)}
onKeyPress={() => setSearchOpen(true)}
action="/search"
// eslint-disable-next-line
role="searchbox"
onSubmit={handleSubmit}
>
<input
value={inputText}
onChange={e => setInputText(e.target.value)}
className="search-form__input"
name="filter"
type="text"
/>
{inputText.length > 150 ? <span style={{color:red}}>Sorry! Maximum length 150 </span> : ''}
<button
className="search-form__button"
type="submit"
aria-label="Header search button"
/>
</form>
);
};
另一種方法是創建一個無效的變數狀態,如果值無效,則在提交函式時將 true 分配給無效變數,然后根據無效值顯示訊息
uj5u.com熱心網友回復:
你能在你的if陳述句中添加代碼嗎?像這樣:
if (inputText.length >= 150) {
window.open("https://www.your-window.com");
e.preventDefault();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/338450.html
標籤:javascript 反应 反应原生
