【发布时间】:2022-01-19 19:25:34
【问题描述】:
我有一个表单,当在表单外调用函数且没有按钮(它与按钮一起使用)时,我想提交 (POST)。
我试过用这个:document.getElementById('liked').submit();
但它只是将其粘贴到网址中:http://localhost:3000/?postId=108&userId=1
我曾尝试将method="post" 放在表单标签中,但随后显示“CANNOT POST”
帖子是用 Axios 完成的。
除此之外,我希望它不要重新加载页面/组件
这是我的表格:
<form id="liked" name="liked" onSubmit={handlePost}>
<input hidden name="postId" id="postId" value={product.id} />
<input hidden name="userId" id="userId" value={currentUser.id} />
</form>;
这是我调用 Axios post 函数的回调:
const handlePost = useCallback((event) => {
event.preventDefault();
context.postBookmark(event.target);
});
这是我要提交表单的地方:
const onSwipe = (direction) => {
if (direction == "right") {
// SUBMIT HERE
document.getElementById("liked").submit();
}
}
【问题讨论】:
-
理想情况下,您应该有一个可以调用的函数来执行提交,它不依赖于事件目标。然后,您可以在想要提交数据时调用该函数,无论您喜欢什么事件。
标签: javascript html reactjs