gpt4 book ai didi

javascript - React 中是否可以使用按钮单击事件来触发表单提交?

转载 作者:行者123 更新时间:2023-12-01 00:13:16 25 4
gpt4 key购买 nike

在 React 中是否可以使用常规按钮组件上的单击事件来触发隐藏表单提交按钮的单击/表单的提交,并且所有表单值和更新的索引都完好无损?

我有一个包含一系列步骤(如向导)的应用程序,每个步骤中都有一个表单,该表单有自己的隐藏提交按钮。当单击 ButtonNext (以及最后一步的 ButtonFinal)时,是否有办法触发对隐藏表单提交按钮的单击,以便 onSubmit 运行,然后将表单值和索引值发送到 handleSubmit 函数?

我可能可以使用 data-key 属性访问隐藏的提交按钮。

编辑:ButtonNextButtonFinal 是 DOM 中表单的直接兄弟,无法添加到表单中。

import React, { useState } from 'react'
import { Row, Col } from 'react-styled-flexboxgrid'
import { Form, ButtonNext, ButtonPrevious, ButtonFinal } from './style'

const Application = ({ steps }) => {
const [currentStepNum, setCurrentStepNum] = useState(0)
const [previousStepName, setPreviousStepName] = useState(steps[0].step_name)
const [nextStepName, setNextStepName] = useState(steps[1].step_name)
const [formValues, setFormValues] = useState(null)

const handleSubmit = (values, step) => {
setFormValues(values)
setStep(step)
}

const handleClick = (event, step) => {
event.preventDefault()
setStep(step)
}

const setStep = step => {
step = parseInt(step)
setCurrentStepNum(step)

if (step > 0) {
setPreviousStepName(steps[step - 1].step_name)
}

if (step < steps.length - 1) {
setNextStepName(steps[step + 1].step_name)
}
}

return (
<>
<div>
{steps.map((step, index) => {
return (
<div key={index}>
{currentStepNum == index && (
<>
{step.form.length > 0 && (
<Form
action="/"
fields={fields}
onSubmit={(values) => {
handleSubmit(values, [index + 1])
}}
/>
)}
{index > 0 && (
<ButtonPrevious
onClick={event => {
handleClick(event, [index - 1])
}}
>
Back to {previousStepName}
</ButtonPrevious>
)}
{index < steps.length - 1 && (
<ButtonNext
onClick={Trigger onSubmit here}
>
Next: {nextStepName}
</ButtonNext>
)}
{index == steps.length - 1 && (
<ButtonFinal
onClick={Trigger onSubmit here}
>
FINAL SUBMIT BUTTON PLACEHOLDER
</ButtonFinal>
)}
</>
)}
</div>
)
})}
</div>
</>
)
}

export default Application

最佳答案

如果您有一个设置了 onSubmit 的表单元素,则默认情况下该表单中的任何按钮都会提交该表单。您可以通过为该按钮定义 onClick 函数并在传递的事件上调用 preventDefault() 来禁用此默认行为。

关于javascript - React 中是否可以使用按钮单击事件来触发表单提交?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59937584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com