React - 使用useRef触发表单提交

8

您好,我正在尝试在表单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>)

我希望在提交表单或执行表单操作之前,能够向服务器发起一些调用并获取返回结果。

5个回答

14

你尝试过以下方法吗:

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

?


4
从React 17开始,您需要为事件添加cancelablebubbles属性。否则,接受的答案中的解决方案将无法正常工作。这是由于事件委托中的一些变化引起的。请参考更改事件委托
formEl?.current.dispatchEvent(
  new Event("submit", { cancelable: true, bubbles: true })
);

I found the answer here.


3
与我合作
  const fromRef = useRef<HTMLFormElement>()  

表格:

<form ref={fromRef} onSubmit={handleSubmit(onSubmit)}>

按钮:

  <Button onClick={() => {
      fromRef.current.requestSubmit()

    }} colorScheme='blue'>Save</Button>

0

尝试

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

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

感谢您的回复,由于某种原因,即使返回true,e.preventDefault()也不再触发表单上的操作。 - J.Naude
是的,我以为你想要手动处理所有东西。 - Qchmqs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接