[英]Why is the preventDefault() method not working for me in my react application?
I used a form to capture input from user.我使用了一个表单来捕获用户的输入。 But once the user clicks on the submit button, the page reloads.
但是一旦用户点击提交按钮,页面就会重新加载。 I don't want it to reload.
我不希望它重新加载。 That was why I decided to use preventDefault() method.
这就是我决定使用 preventDefault() 方法的原因。 How can I get this to work?
我怎样才能让它发挥作用?
const handleHeaderValueUpdate = async ( headerId, e) =>{
e.preventDefault()
console.log(headerId)
setUpdating(true)
const updatedHeaderValue = {
username: user.username,
websiteName,
sitesubName,
};
if(file){ //logic behind uploading image and the image name
const data = new FormData();
const filename = Date.now() + file.name;
data.append("name", filename);
data.append("file", file);
updatedHeaderValue.headerImg = filename;
try{
await axios.post("/upload", data)//handles the uploading of the image
//setUpdated(true)
}catch(err){
dispatch({type: "UPDATE_FAILURE"})
}
}
try{
await axios.put("/headervalue/" + headerId, updatedHeaderValue)
setUpdating(false);
setTextUpdate(true)
//setUpdated(true)
}catch(err){
console.log(err)
}
}
Here is part of the form:这是表格的一部分:
<form onSubmit={()=>handleHeaderValueUpdate(headerId)} className="dashboard-form">
<div className='dasboard-input-div'>
<p className="dashboard-label">Website Name</p>
{dashboardEditMode ? <input className="dashboard-input" type="text" placeholder={singleValues.websiteName} autoFocus
onChange={(e) => setWebsiteName(e.target.value)}
required
/> :
<input className="dashboard-input" type="text" placeholder= {singleValues.websiteName} readOnly/>
}
</form>
Here is the submit button这是提交按钮
{dashboardEditMode && <button className={updating ? "updateModeBTN-unclick updateModeBTN" : "updateModeBTN"} type="submit">Update</button>}
The problem is you do not send the event to the handleHeaderValueUpdate
function.问题是您没有将事件发送到
handleHeaderValueUpdate
函数。 You should change:你应该改变:
<form onSubmit={()=>handleHeaderValueUpdate(headerId)}
to:到:
<form onSubmit={(e) => handleHeaderValueUpdate(headerId, e)}
You can take a look at this sandbox for a live working example.您可以查看此沙箱以获取实时工作示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.