簡體   English   中英

在沒有jQuery AJAX的情況下在React中提交表單

[英]Submit form in React without jQuery AJAX

我正在嘗試使用formspree在我使用React構建的靜態站點中提交表單。 我已經接近了,但現在完全迷失了。

我正在嘗試使用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}

任何幫助將不勝感激。 真的想學習。

我可能錯了,但從我看到你幾乎不需要在這里使用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

你可以嘗試獲取

示例承諾代碼:

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庫不允許“ref”用於<Input />組件。 所以我選擇了常規的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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM