我试图在我使用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/[email protected]';




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}


任何帮助将不胜感激。真的想学习。

最佳答案

我可能是错的,但是从我看来,您几乎不需要在这里使用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 email重命名为url

07-24 15:06