在反应中创建数据后如何清除输入字段并重置选择选项
我正在尝试创建一个包含某些字段的表单。但我不知道如何在插入数据后清除输入字段,我也希望我的选择选项返回到默认的“选择选项”。
const AddBook = () => {
const [authors, setAuthors] = useState([]);
const [book, setBook] = useState([]);
const { loading, data } = useQuery(getAuthorsQuery)
const [addBook] = useMutation(addBookMutation)
const handleSubmit = (e) => {
e.preventDefault();
addBook({
variables: {
name: book.name,
genre: book.genre,
authorId: book.authorId
},
refetchQueries:[{query:getBooksQuery}]
})
}
const handleChange = (e) => {
setBook({...book,[e.target.name]: e.target.value})
}
useEffect(() => {
if (!loading) {
setAuthors(data.authors)
}
}, [data, loading]);
return (
<form id="add-book" onSubmit={handleSubmit}>
<div className='field'>
<label>Book name</label>
<input type="text" name="name" onChange={handleChange}/>
</div>
<div className='field'>
<label>Genre</label>
<input type="text" name="genre" onChange={handleChange}/>
</div>
<div className='field'>
<label>Author</label>
<select name="authorId" onChange={handleChange}>
<option>Select Option</option>
{authors.map(author => <option name="authorId" key={author.id} value={author.id}>{author.name}</option>)}
</select>
</div>
<button>Add Book</button>
</form>
)
};
导出默认AddBook
I am trying to create a form with some fields. but I don't know how to clear my input field after inserting data and I would also like my select option to go back to the default "Select option".
const AddBook = () => {
const [authors, setAuthors] = useState([]);
const [book, setBook] = useState([]);
const { loading, data } = useQuery(getAuthorsQuery)
const [addBook] = useMutation(addBookMutation)
const handleSubmit = (e) => {
e.preventDefault();
addBook({
variables: {
name: book.name,
genre: book.genre,
authorId: book.authorId
},
refetchQueries:[{query:getBooksQuery}]
})
}
const handleChange = (e) => {
setBook({...book,[e.target.name]: e.target.value})
}
useEffect(() => {
if (!loading) {
setAuthors(data.authors)
}
}, [data, loading]);
return (
<form id="add-book" onSubmit={handleSubmit}>
<div className='field'>
<label>Book name</label>
<input type="text" name="name" onChange={handleChange}/>
</div>
<div className='field'>
<label>Genre</label>
<input type="text" name="genre" onChange={handleChange}/>
</div>
<div className='field'>
<label>Author</label>
<select name="authorId" onChange={handleChange}>
<option>Select Option</option>
{authors.map(author => <option name="authorId" key={author.id} value={author.id}>{author.name}</option>)}
</select>
</div>
<button>Add Book</button>
</form>
)
};
export default AddBook
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决方案
Solution