使用 Formik,有一些方法可以为您的表单做后台工作。这基本上可以通过将handleChange 或handleBlur 道具传递给表单组件来实现。
例如,我相信您的表单元素中会有其他输入,而不仅仅是验证码 (if it's just a captcha in the form, then do let me know! - this can also be solved)
所以当你有其他元素时,你可以确保使用Formik的一些API来处理自动触发:
正如我所见,有很多方法可以通过他们的 API 处理这个问题:https://formik.org/docs/api/formik
我尝试实现它的方法是在所有字段上添加onBlur 的侦听器,然后检查是否存在 reCaptcha 值。基于此,我触发执行验证码并确保将提交值设置为 true:
const handleBlur = (e) => {
console.log("$$$$", props.isSubmitting);
if (!props.values.recaptcha) {
this._reCaptchaRef.current.execute();
props.setSubmitting(true);
}
props.handleBlur(e);
};
这里是 CodeSandbox 链接:https://codesandbox.io/s/silly-saha-qq7hg?file=/src/App.js
这显示了处理一个字段的onBlur 并在后台触发它的工作模型。如果您注意到,您还可以使用isSubmitting 和setSubmitting 禁用和启用提交按钮。
同时设置validateOnChange={false} 和validateOnBlur={false},因为不需要验证验证码的更改或模糊。
在此处粘贴代码以供您浏览:
import React, { Component, createRef } from "react";
import ReCAPTCHA from "react-google-recaptcha";
import { Formik } from "formik";
import * as yup from "yup";
const TEST_SITE_KEY = "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI";
export default class MyForm extends Component {
constructor(props) {
super(props);
this._validationSchema = yup.object().shape({
recaptcha: yup.string().required(),
name: yup.string().required(),
address: yup.string().required()
});
this._initialValues = { recaptcha: "", name: "", address: "" };
this._reCaptchaRef = createRef();
}
render() {
return (
<Formik
validationSchema={this._validationSchema}
initialValues={this._initialValues}
validateOnChange={false}
validateOnBlur={false}
onSubmit={(values) => console.log(values)}
>
{(props) => {
const handleBlur = (e) => {
console.log("$$$$", props.isSubmitting);
if (!props.values.recaptcha) {
this._reCaptchaRef.current.execute();
props.setSubmitting(true);
}
props.handleBlur(e);
};
return (
<form onSubmit={props.handleSubmit}>
<label>Name: </label>
<input
type="text"
onChange={props.handleChange}
value={props.values.name}
name="name"
onBlur={handleBlur}
/>
<label>Address: </label>
<input
type="text"
onChange={props.handleChange}
value={props.values.address}
name="address"
onBlur={handleBlur}
/>
<ReCAPTCHA
ref={this._reCaptchaRef}
sitekey={TEST_SITE_KEY}
onChange={(value) => {
console.log("$$$$", props.isSubmitting, value);
props.setFieldValue("recaptcha", value);
props.setSubmitting(false);
}}
size="invisible"
/>
<button type="submit" disabled={props.isSubmitting}>
SUBMIT
</button>
{props.errors.name && <div>{props.errors.name}</div>}
</form>
);
}}
</Formik>
);
}
}