我正在尝试在gatsby和react中使用这个带有https://www.npmjs.com/package/react-google-recaptcha包的https://react-hook-form.com/get-started npm包。我想使用不可见的recaptcha,看起来我必须执行recaptcha,这是我试图通过创建react引用来执行的,但它显示rec.current为空,而不是引用确定要做什么。onSubmit函数是我得到null结果的地方,我假设我可以在这里触发验证码,然后取回验证码的值,以便稍后在我的lambda函数中发送给google进行验证。
提前感谢
到目前为止,我的代码如下
import React, { useState } from "react"
import Layout from "../components/layout"
import Img from "gatsby-image"
import { graphql, Link } from "gatsby"
import { CartItems } from "../components/cart"
import { useForm } from "react-hook-form"
import ReCAPTCHA from "react-google-recaptcha"
const StoreDetails = ({ data }) => {
const { register, handleSubmit, watch, errors } = useForm()
const recaptchaRef = React.createRef()
const onSubmit = data => {
console.log(recaptchaRef)
recaptchaRef.current.execute() //this shows up null
}
function onChange(value) {
console.log("Captcha value:", value)
}
function error(value) {
alert(value)
}
return (
<>
{data.allSanityProducts.edges.map(({ node: product }, i) => {
return (
<React.Fragment key={i}>
<Item>
<Img
fluid={product.featureImage && product.featureImage.asset.fluid}
/>
<div>
...
<form onSubmit={handleSubmit(onSubmit)}>
{/* register your input into the hook by invoking the "register" function */}
<input name="example" defaultValue="test" ref={register} />
{/* include validation with required or other standard HTML validation rules */}
<input
name="exampleRequired"
ref={register({ required: true })}
/>
{/* errors will return when field validation fails */}
{errors.exampleRequired && (
<span>This field is required</span>
)}
<ReCAPTCHA
className="captchaStyle"
sitekey="obsf"
onChange={onChange}
onErrored={error}
badge={"bottomright"}
size={"invisible"}
ref={recaptchaRef}
/>
<input type="submit" />
</form>
</div>
</Item>
</React.Fragment>
)
})}
{close && <CartItems />}
</>
)
}
const WithLayout = Component => {
return props => (
<>
<Layout>
<Component {...props} />
</Layout>
...
</>
)
}
export default WithLayout(StoreDetails)
export const query = graphql`
query StoreDeatailsQuery($slug: String!) {
...
}
`发布于 2020-08-26 17:27:28
您永远不会用任何值填充引用。在以下位置初始设置为null:
const recaptchaRef = React.createRef()你必须等待谷歌的响应用一个值填充recaptchaRef。换句话说,您需要使用基于promise的方法,通过使用executeAsync()和async函数来填充它:
const onSubmit = async (data) => {
const yourValue = await recaptchaRef.current.executeAsync();
console.log(yourValue)
}您可以查看有关react-google-recaptcha documentation中公开的props的更多详细信息。
https://stackoverflow.com/questions/63541542
复制相似问题