我有一个名为SignUp
它的功能组件,它使用 google recaptcha 来保护注册表单。
Signup
创建一个指向Recaptcha
组件的 ref 并声明一个onResolved
指向函数方法的回调函数onRecaptchaResolved
问题是当onRecaptchaResolved
在 Recaptcha 执行后被调用时,我们输入的值不是最新状态,而是useState
在我们的例子中设置的初始值"hi"
import React, { useState } from 'react';
import styled from 'styled-components';
import Recaptcha from 'react-google-invisible-recaptcha';
const Input = styled.input``
function SignUp({dispatch}) {
const [inputValue, setInputValue] = useState("hi");
let recaptcha = null; // this will be our ref
const formSubmit = () => {
recaptcha.execute()
}
const onRecaptchaResolved = ( recaptchaToken) => {
console.log(inputValue); // always logs; "hi"
}
return (
<>
<Input
placeholder="you@example.com"
type="text"
value={inputValue}
onChange={e => setInputValue(e.target.value)
}
/>
<Recaptcha
ref={ ref => recaptcha = ref }
sitekey={ "{MY_SITE_KEY}" }
onResolved={recaptchaToken =>{ onRecaptchaResolved(recaptchaToken)} }
/>
<SubmitButton onClick={formSubmit}> Submit email</SubmitButton>
</>
)
}
如何确保读入的输入值onRecaptchaResolved
是更新后的值?