4

美好的一天,所以我试图在表单 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>)

本质上是想在提交表单或执行表单操作之前对服务器进行一些调用并获取结果。

4

3 回答 3

6

你有没有尝试过:

formEl.current && formEl.current.submit();

?

于 2020-07-21T13:52:55.253 回答
0

传递事件然后阻止其默认操作

const performSubmit =(e) => {

 // stop the form from actually submitting
 e.preventDefault();

 //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={(e) => performSubmit(e)} id="x1" method="POST" action="https://url.aspx" target="_top">
    <input value={config.param}/>
    <button type="submit"> Submit</button>
</form>)
于 2020-07-21T14:03:52.353 回答
0

尝试

form?.current.dispatchEvent(new Event("submit"));
于 2022-01-31T09:47:58.920 回答