您好,我正在尝试在表单action="POST"执行之前进行中间函数操作。我尝试了两种方法,首先是使用onSubmit={functionName},但即使在onSubmit函数中返回false,表单仍然执行该操作。其次,我尝试使用useRef来分发提交事件,但没有任何反应? 我需要实际上进行服务器端调用以获取将发布的表单值的配置,不幸的是我使用的外部API需要以这种方式提交表单。请帮忙解决问题,非常感谢。
尝试1:
const performSubmit =() => {
//Using onSubmit and then only performing the return after the axios call is done
axiosCallFunction.then((res) => {
setConfig(res.data)
return true
}).catch((error)) => {
//Dont submit form
return false
})
}
return (
<form name="form" onSubmit={performSubmit} id="x1" method="POST" action="https://url.aspx" target="_top">
<input value={config.param}/>
<button type="submit"> Submit</button>
</form>)
尝试2
const formEl = useRef();
const performSubmit =() => {
//Currently not calling the submit on the form
formEl.current.dispatchEvent(new Event("submit"))
}
return (
<form name="form" ref={formEl} id="x1" method="POST" action="https://url.aspx" target="_top">
<input value={config.param}/>
<button onClick={performSubmit} />
</form>)
我希望在提交表单或执行表单操作之前,能够向服务器发起一些调用并获取返回结果。