在没有 jQuery AJAX 的情况下在 React 中提交表单

IT技术 javascript reactjs ecmascript-6 es6-promise
2021-05-17 05:20:08

我正在尝试在我使用 React 构建的静态站点中使用 formspree 提交我的表单。我已经接近了,但现在完全迷失了。

我正在尝试使用 ES6 Promise 功能,但不知道如何完成它。

这是我当前的代码:

import React from 'react';
import { Link } from 'react-router';


import { prefixLink } from 'gatsby-helpers';
import { config } from 'config';

import Headroom from 'react-headroom';

import Nav from './nav.js';

import '../css/main.scss';

import Modal from 'boron/DropModal';

import {Input, Label,Textarea, Button} from 're-bulma';

const modalStyle = {
  minHeight: '500px',
  backgroundColor: '#303841'
};

const backdropStyle = {
  backgroundColor: '#F6C90E'
};

const contentStyle = {
  backgroundColor: '#303841',
  padding: '3rem'
};

const gotcha = {
  display: 'none'
};

const email = 'https://formspree.io/dillonraphael@gmail.com';




export default class RootTemplate extends React.Component {
  static propTypes = {
    location: React.PropTypes.object.isRequired,
    children: React.PropTypes.object.isRequired,
  }

  static contextTypes = {
    router: React.PropTypes.object.isRequired,
  }

  constructor() {
    super();
    this.showModal = this.showModal.bind(this);
  }

  showModal () {
    this.refs.modal.show();
  }

  formSubmit(e) {
    e.preventDefault();
    let data = {
      name: this.refs.name.value,
      email: this.refs.email.value,
      message: this.refs.message.value
    }
    return new Promise((resolve, reject) => {
      const req = new XMLHttpRequest();
      req.open('POST', email);
    });
    console.log(data);
  }

  render() {
    return (
      <div>
        <Headroom>
          <Nav showModal={this.showModal}/>
        </Headroom>
        <Modal ref="modal" modalStyle={modalStyle} contentStyle={contentStyle} backdropStyle={backdropStyle}>
          <form ref='contact_form' onSubmit={::this.formSubmit}>
            <Label>Name:</Label>
            <Input ref="name" />
            <Label>Email:</Label>
            <Input ref="email" type="email"/>
            <Label>Message:</Label>
            <Textarea ref="message" />
            <Input type="text" name="_gotcha" style={gotcha}/>
            <Button buttonStyle="isOutlined" color="isWarning">Submit</Button>
          </form>
        </Modal>
        {this.props.children}
      </div>
    );
  }
}

我目前也收到此错误:

Object {name: undefined, email: undefined, message: undefined}

任何帮助将不胜感激。真的努力学习了。

3个回答

我可能是错的,但从我看来,您几乎不需要在这里使用 Promise。试试这个

formSubmit = (e) => {
    e.preventDefault();
    const {name, email, message} = this.refs
    const formData = new FormData();
    formData.append("name", name.value);
    formData.append("email", email.value);
    formData.append("message", message.value);
    const req = new XMLHttpRequest();
    req.open('POST', url);
    req.send(formData);
  }

我重命名了 previosley 定义cosnt emailurl

你可以试试fetch

示例Promise代码:

var form = document.querySelector('form')


function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response
  } else {
    var error = new Error(response.statusText)
    error.response = response
    throw error
  }
}

function parseJSON(response) {
  return response.json()
}

    fetch('/users',{
       method: 'POST',
       body: new FormData(form)
       })
      .then(checkStatus)
      .then(parseJSON)
      .then(function(data) {
        console.log('request succeeded with JSON response', data)
      }).catch(function(error) {
        console.log('request failed', error)
      })

我终于弄明白了。感谢大家的帮助。主要问题是 re-bulma npm 库不允许对其<Input />组件使用“ref” 所以我选择了常规的 html 输入。我也在使用 Axios 库来处理请求。这是我在下面更新的代码,希望这对某人有所帮助。

formSubmit (e){
    e.preventDefault();

    let form = document.querySelector('form') 

    let name = this.nameRef.value
    let email = this.emailRef.value
    let message = this.messageRef.value


    axios.post(url, {
      data: {
        name: name,
        email: email,
        message: message
      }
    })
    .then(function (response) {
      console.log(response);
      form.reset()
    })
    .catch(function(error) {
      console.log(error);
      form.reset()
    });
  }

和表单标记:

 <form onSubmit={::this.formSubmit}>
     <div className="formInput">
        <input type="text" placeholder="Name" ref={(input) => this.nameRef = input} />
      </div>
      <div className="formInput">
        <input type="email" placeholder="Email" ref={(input)=> this.emailRef = input} />
      </div>
      <div className="formInput">
        <textarea placeholder="Message" ref={(input) => this.messageRef = input} />
      </div>
      <input type="text" name="_gotcha" style={gotcha}/>
      <div className="formInput">
        <Button buttonStyle="isOutlined" color="isWarning">Submit</Button>
      </div>
  </form>