React-使用useRef触发表单提交

时间:2020-07-21 13:47:58

标签: reactjs forms react-hooks onsubmit use-ref

早上好,所以我尝试在执行表单action =“ POST”之前执行中间功能。香港专业教育学院首先尝试了两件事onSubmit = {functionName},但即使在onSubmit函数中我返回false,表单也总是执行操作。其次,香港专业教育学院一直试图使用Ref代替以编程方式调度Submit事件,但没有任何反应?我本质上必须做一个服务器端调用才能获取要发布的表单值的配置,不幸的是,我使用的外部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>)

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

2 个答案:

答案 0 :(得分:2)

您尝试过吗:

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

答案 1 :(得分: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>)