React - 使用 useRef 触发表单提交

React - Trigger form submit using useRef

美好的一天,所以我正在尝试在表单 action="POST" 发生之前执行一个中间函数。我首先尝试了两件事 onSubmit={functionName} 但即使在 onSubmit 函数中我 return false,表单也总是执行该操作。其次,我一直在尝试使用 Ref 而不是以编程方式分派提交事件,但没有任何反应?我基本上必须执行服务器端调用以获取发布的表单值的配置,不幸的是我使用的外部 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>)

主要是想在提交表单或执行表单操作之前调用服务器并取回结果。

你试过了吗:

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

?

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

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>)

尝试

form?.current.dispatchEvent(new Event("submit"));

Starting from React 17 you have to add cancelable and bubbles properties to your event. Otherwise, the solution from the accepted answer won't work. It's caused by some changes in event delegation.

formEl?.current.dispatchEvent(
  new Event("submit", { cancelable: true, bubbles: true })
);

我找到了答案