【问题标题】:React Netlify form does not submitReact Netlify 表单未提交
【发布时间】:2021-01-20 18:24:07
【问题描述】:

我正在创建一个用于培训的个人网站,我想为/contact URL 使用 Netlify 表单提交我尝试只添加 netlifynetlify='true' 和其他类似的东西,但我每次尝试时都会给我 404 错误使用 Netlify 表单提交,但无论我做什么似乎都不起作用,我遵循了几个教程和 repos 但仍然不起作用。它只是给出 404 错误和其他东西; 请查看我的 github 仓库,

My GitHub Repo's Link 这是我的Contact.js 组件;

import React, { Fragment, useState } from 'react';
import '../../App.css';
const encode = (data) => {
  return Object.keys(data)
    .map((key) => encodeURIComponent(key) + '=' +         encodeURIComponent(data[key]))
.join('&');
};
const Contact = () => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [text, setText] = useState('');

  const handleSubmit = (e) => {
    fetch('/', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: encode({
        'form-name': 'contact',
          name: name,
           email: email,
          text: text,
          }),
        })
        .then((res) => {
        console.log(res);
      })
     .catch((error) => alert(error));

     e.preventDefault();
    };
 return (
   <Fragment>
  <div className='contact'>
    <div className='contact-wrapper'>
      <div className='title'>
        <span>Contact me</span>
      </div>
      <div className='contact-form'>
        <form
          className='myform'
          method='POST'
          name='contact'
          data-netlify='true'
          onSubmit={(e) => handleSubmit(e)}
        >
          <input type='hidden' name='form-name' value='contact'></input>

          <input
            type='text'
            placeholder='Your Name'
            name='name'
            value={name}
            onChange={(e) => setName(e.target.value)}
          ></input>
          <input
            type='email'
            placeholder='Your E-Mail'
            name='email'
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          ></input>
          <textarea
            placeholder='Your message'
            name='message'
            value={text}
            onChange={(e) => setText(e.target.value)}
          ></textarea>
          <button type='submit'>Send</button>
        </form>
      </div>
    </div>
     </div>
   </Fragment>
   );
};

export default Contact;

【问题讨论】:

    标签: reactjs forms netlify


    【解决方案1】:

    Netlify 的表单通过其服务器在部署时编辑您的 html 以添加提交表单的钩子来工作。

    对于 React 应用,表单在部署时不会在 html 中可见,因此这不起作用。

    Netlify 有关于如何使用 SPA 设置表单的指南,请在此处查看:https://www.netlify.com/blog/2017/07/20/how-to-integrate-netlifys-form-handling-in-a-react-app/

    【讨论】:

    • 经过长时间的研究,我发现了这一点,我只是在我的public/index.html 中添加了一个静态表单,它就成功了!现在我正在尝试实施 recaptcha,但感谢您回答我的问题
    猜你喜欢
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 2020-12-25
    • 2020-07-30
    • 2021-08-15
    • 1970-01-01
    相关资源
    最近更新 更多