我有一個表單,我想知道onSubmit時輸入值是否為空,它們沒有發送。我試圖通過 if 的 handleInputChange 來做到這一點,但這不起作用:
const handleInputChange = (e: React.FormEvent<HTMLInputElement>) => {
if ((e.target as HTMLInputElement).value) {
setNewPost({
...newPost,
[(e.target as HTMLInputElement).name]: (e.target as HTMLInputElement).value
})
}
e.preventDefault();
};
所有代碼:
const New: React.FC = () => {
// const [newPost, setNewPost] = useState("");
const [newPost, setNewPost] = useState({
title: '',
author: '',
content: ''
})
const handleInputChange = (e: React.FormEvent<HTMLInputElement>) => {
if ((e.target as HTMLInputElement).value) {
setNewPost({
...newPost,
[(e.target as HTMLInputElement).name]: (e.target as HTMLInputElement).value
})
}
e.preventDefault();
};
const createPost = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault(); //Detiene el formulario para que no actualize la página
setPost(newPost)
}
return (
<div className="containerHomepage">
<form className="formulari" onSubmit={createPost}>
<div className="containerBreadCrumb">
<ul className="breadCrumb">
<li>Posts</li>
</ul>
</div>
<div className="containerTitleButton">
<input
className=""
type="text"
placeholder='Post title'
name="title"
onChange={handleInputChange}
></input>
<button
className="button"
type="submit"
>Save</button>
</div>
<div className="containerEdit">
<input
className=""
type="text"
placeholder='Author'
name="author"
onChange={handleInputChange}
></input>
<input
className=""
type="text"
placeholder='Content'
name="content"
onChange={handleInputChange}
></input>
</div>
</form>
</div>
);
};
// ========================================
export default New;
uj5u.com熱心網友回復:
您的電流handleInputChange使用戶無法將任何輸入更改為空字串。 這里有一個主要的可用性缺陷。一旦用戶輸入第一個字符,他們就不能洗掉它! 您應該允許輸入為空,但除非填寫所有欄位,否則不允許提交表單。
您可以使用e.currentTarget而不是e.target避免大量型別斷言。這個問題有更多資訊,但這里重要的是它e.currentTarget永遠是HTMLInputElement.
const handleInputChange = (e: React.FormEvent<HTMLInputElement>) => {
setNewPost({
...newPost,
[e.currentTarget.name]: e.currentTarget.value
});
};
@rax 的答案是正確的,但我會沿著這條路走得更遠。
在任何時間點,您都可以通過查看當前狀態來知道表單是否有效newPost。 有很多方法可以寫這個,它們都做同樣的事情:
const isValid = Boolean(newPost.title && newPost.author && newPost.content);
使用型別強制。除空字串外,所有字串都是真實的。
const isValid = newPost.title !== '' && newPost.author !== '' && newPost.content !== '';
來自@Vladimir Trotsenko 的回答。
const isValid = Object.values(newPost).every(value => value.length > 0)
回圈遍歷所有值,newPost因此如果添加額外欄位,則無需更改任何內容。
您可以使用此isValid變數有條件地禁用“保存”按鈕。
<button type="submit" disabled={!isValid}>Save</button>
您還可以使用isValid向用戶顯示訊息或其他可見反饋。例如,您可以在將滑鼠懸停在禁用按鈕上時顯示一條訊息,告訴他們為什么它已被禁用。
<button
type="submit"
disabled={!isValid}
title={isValid ? "Create your post" : "All fields must be filled out."}
>
Save
</button>
我正在檢查if (isValid)該createPost功能以確保安全,但我認為這實際上不是必需的,因為如果禁用提交按鈕,則不會提交表單(即使按 Enter 鍵)。
const createPost = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault(); // stop the form from reloading the page.
if (isValid) {
// put your actual code here instead.
alert("submit success");
}
};
完整代碼:
import React, { useState } from "react";
const New: React.FC = () => {
const initialState = {
title: "",
author: "",
content: ""
};
const [newPost, setNewPost] = useState(initialState);
const isValid = Boolean(newPost.title && newPost.author && newPost.content);
const handleInputChange = (e: React.FormEvent<HTMLInputElement>) => {
setNewPost({
...newPost,
[e.currentTarget.name]: e.currentTarget.value
});
};
const createPost = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault(); //stop the form from reloading the page
if (isValid) {
alert("submit success");
}
};
return (
<div className="containerHomepage">
<form className="formulari" onSubmit={createPost}>
<div className="containerBreadCrumb">
<ul className="breadCrumb">
<li>Posts</li>
</ul>
</div>
<div className="containerTitleButton">
<input
className=""
type="text"
placeholder="Post title"
name="title"
onChange={handleInputChange}
value={newPost.title}
/>
<button
className="button"
type="submit"
disabled={!isValid}
title={
isValid ? "Create your post" : "All fields must be filled out."
}
>
Save
</button>
</div>
<div className="containerEdit">
<input
className=""
type="text"
placeholder="Author"
name="author"
onChange={handleInputChange}
value={newPost.author}
/>
<input
className=""
type="text"
placeholder="Content"
name="content"
onChange={handleInputChange}
value={newPost.content}
/>
</div>
</form>
</div>
);
};
export default New;
代碼沙盒
uj5u.com熱心網友回復:
您可以像這樣將輸入值與空字串進行比較:
inputValue === ''
或字串的大小:
inputValue.length === 0
并在您的提交中檢查 if 陳述句中的值。
uj5u.com熱心網友回復:
const createPost = (e) => {
e.preventDefault()
if (newPost.title !== '' && newPost.author !== '' && newPost.content !== '') {
// make api request
} else {
// handle empty fields
}
}
uj5u.com熱心網友回復:
您可以驗證createPost其中應如下所示的空欄位:
const createPost = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault(); //stop the form from reloading the page
if (!newPost.title || !newPost.author || !newPost.content) {
//show some error message
} else {
//perform further action
setPost(newPost);
}
}
如需完整的作業示例,請單擊此處。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/429452.html
標籤:javascript 反应 打字稿 形式 反应钩子
