【发布时间】:2021-10-13 14:29:17
【问题描述】:
我有一个如下的 Formik 表单,它在其原始实现中运行良好。我必须添加的一项额外功能是,当单击提交按钮时,我必须禁用它,以防止双击。我按照example here 定义了一个按钮上的ref={submitBtnRef}。但是在onClick 中插入此代码后,Formik 不再提交,它只是停止。如果我删除这个新代码,一切正常。没有验证错误;我输出 Formik 的errors,它是空的。也没有控制台错误。
const submitForm = async (formValues) => {
const url = '/app/submitAgreement';
let obj = {'formValues': formValues};
await axios.post(url, obj);
}
// Define a Submit Button Ref for disabling in Submit's onClick() below
let submitBtnRef = useRef();
<Formik
enableReinitialize
validationSchema={mySchema}
onSubmit={ (values) => {
submitForm(values); // Calls submitForm() function if there are no errors
}}
initialValues={initialFormValues}
>
{
({handleSubmit, handleChange, handleBlur, setFieldValue, setFieldTouched, values, touched, isValid, errors})
=> (
<Form onSubmit={handleSubmit}> {/* Form starts here */}
..
..
<Button type="submit" ref={submitBtnRef}
onClick={() => {
// If I remove this Ref-Disable code it works, but I need to disable Submit
if(submitBtnRef.current) {
submitBtnRef.current.setAttribute("disabled", "disabled");
}
// The default form-submit method specified in the Formik Form, submitForm(),
// will now be executed if there are no validation errors
}}
>Submit</Button>
..
</Form>
【问题讨论】: