美好的一天,所以我试图在表单 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>)
本质上是想在提交表单或执行表单操作之前对服务器进行一些调用并获取结果。