0

我无法弄清楚为什么我的组件没有按预期工作。由于 Uncaught TypeError,reCAPTCHA 无法验证。单击复选框时 reCAPTCHA 开始验证,但在控制台中被错误消息中断。

我也遵循了本指南,但我遇到了同样的错误。我绝对不确定问题在哪个级别。这个相同的实现在 GatsbyJS 中按预期工作。

控制台错误

对于调试我的问题或为我指明正确方向的任何帮助,我将不胜感激。

我的组件

const ContactForm = () => {
  const [state, setState] = useState('');
  const [buttonDisabled, setButtonDisabled] = useState(true);
  const recaptchaRef = createRef();

  const encode = (data) => {
    return Object.keys(data)
      .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
      .join('&');
  };

  const handleChange = (e) => {
    setState({ ...state, [e.target.name]: e.target.value });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const form = e.target;
    const recaptchaValue = recaptchaRef.current.getValue();
    fetch('/', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: encode({
        'form-name': form.getAttribute('name'),
        'g-recaptcha-response': recaptchaValue,
        ...state,
      }),
    })
      .then(() => {
        e.target.reset();
        alert('Message sent');
      })
      .catch((error) => alert(error));
  };

  return (
    <SectionWrapper id='contact'>
      <GlitchTitle content='Contact Me'/>
      <StyledForm
        className='flex flex-col w-2/4 justify-center items-center'
        name='contact-form'
        method='POST'
        data-netlify='true'
        onSubmit={handleSubmit}
      >
        <input type='hidden' name='form-name' value='contact-form'/>
        <input
          id='text-input'
          type='text'
          name='name'
          placeholder='Name'
          onChange={handleChange}
          required
        />
        <input
          id='email-input'
          type='email'
          name='email'
          placeholder='Email'
          onChange={handleChange}
          required
        />
        <textarea
          className=''
          id='textarea'
          type='text'
          name='message'
          placeholder='Message'
          onChange={handleChange}
          rows={5}
          maxLength={350}
          required
        />
        <button
          className='border-2 m-3 w-1/2 disabled:opacity-40'
          type='submit'
          disabled={buttonDisabled}
        >
          Submit
        </button>
        <ReCAPTCHA
          ref={recaptchaRef}
          sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY}
          id='recaptcha'
          onChange={() => setButtonDisabled(false)}
        />
      </StyledForm>
    </SectionWrapper>
  );
};
4

0 回答 0