我正在尝试禁用表单的“提交”按钮,直到用户单击Google Recaptcha复选框“我不是机器人”
无论如何,还是需要下载特定于Google Recaptcha的React组件?
这是我包含Google Recaptcha的简单组件:
const RecaptchaComponent = () => {
useEffect(() => {
// Add reCaptcha
const script = document.createElement("script");
script.src = "https://www.google.com/recaptcha/api.js"
document.body.appendChild(script);
}, [])
return (
<div
className="g-recaptcha"
data-sitekey="6LeS8_IdfdfLtQzwUgNV4545454lhvglswww14U"
></div>
)
};
这是我表单的onSubmit代码:
const GameForm = () => (
<div className="app">
<Formik
initialValues={{
email: "",
name: "",
title: ""
}}
onSubmit={(values) => {
//new Promise(resolve => setTimeout(resolve, 500));
axios({
method: "POST",
url: "api/gameform",
data: JSON.stringify(values),
});
}}
>
{props => {
const {
values,
isSubmitting,
handleSubmit,
} = props;
return (
<form onSubmit={handleSubmit}>
<div>Your Game</div>
<label htmlFor="title">
Game Title:
</label>
<Field
id="title"
type="text"
values={values.title}
/>
<label htmlFor="name">
Name:
</label>
<Field
id="name"
type="text"
value={values.name}
/>
<label htmlFor="email">
Email:
</label>
<Field
id="email"
name="email"
type="email"
value={values.email}
/>
<div>
<ReCAPTCHA
sitekey="6LeS8_IUAAAAAhteegfgwwewqe223"
onChange={useCallback(() => setDisableSubmit(false))}
/>
</div>
<div>
<Button type="submit">
Submit
</Button>
</div>
</form>
);
}}
</Formik>
</div>
);
答案 0 :(得分:1)
您不需要使用react component,但是更容易。
export const MyForm = () => {
const [disableSubmit,setDisableSubmit] = useState(true);
return (
... rest of your form
<ReCAPTCHA
sitekey="6LeS8_IdfdfLtQzwUgNV4545454lhvglswww14U"
onChange={useCallback(() => setDisableSubmit(false))}
/>
<button type="submit" disabled={disableSubmit}>Submit</button>
)
}
编辑:
我最大的烦恼之一是看到React教程,作者鼓励开发人员使用返回JSX的函数,而不仅仅是使用功能组件。
Formik的“儿童作为功能”模式是很粗略的(react-router-dom也是一样)-它应该是一个组件:
const GameForm = () => {
return <Formik ...your props>{props => <YourForm {...props}/>}</Formik>
}
const YourForm = (props) => {
const [disableSubmit,setDisableSubmit] = useState(true);
... everything inside the child function in `GameForm`
}