1

我有一个名为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是更新后的值?

4

1 回答 1

2

react-google-invisible-recaptcha似乎存储了提供的初始值,除非重新安装onResolved,否则不会更新它。<Recaptcha>https://github.com/szchenghuang/react-google-invisible-recaptcha/blob/master/src/index.js#L41

确认这一点的最简单方法是key<Recaptcha>更改时设置一个inputValue更改。

于 2020-01-16T12:40:54.690 回答