React - 使用 useRef 触发表单提交

J.N*_*ude 9 forms onsubmit reactjs react-hooks use-ref

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

Run Code Online (Sandbox Code Playgroud)

尝试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>)
Run Code Online (Sandbox Code Playgroud)

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

小智 14

你有没有尝试过:

formEl.current && formEl.current.submit();
Run Code Online (Sandbox Code Playgroud)


cal*_*inf 5

从 React 17 开始,您必须向事件添加cancelable和属性。bubbles否则,已接受答案的解决方案将不起作用。这是由事件委托的一些变化引起的。

formEl?.current.dispatchEvent(
  new Event("submit", { cancelable: true, bubbles: true })
);
Run Code Online (Sandbox Code Playgroud)

我在这里找到了答案。