JavaScript Fetch API для почтового запроса, чтобы отправить данные из формы ReactJS
// App.js
импортировать React, {Component} из "react";
import ‘./App.css’;
класс экспорта по умолчанию. Приложение расширяет компонент {
конструктор(){
супер();
this.state = {имя: ’’, электронная почта: ’’}
}
handleChange = event = ›{
this.setState ({[event.target.name]: event.target.value})
}
handleSubmit = event = ›{
event.preventDefault ();
console.log («Имя пользователя:« + this.state.name) »
console.log («Электронная почта пользователя:« + this.state.email »)
const url = ”https://jsonplaceholder.typicode.com/users/”
const data = {имя: this.state.name, электронная почта: this.state.email}
fetch (url, {method: "POST", // или "PUT"
body: JSON.stringify (data), // данные могут быть `string` или {object}!
заголовки: {‘Content-Type’: ‘application / json’}})
.then (res = ›res.json ())
.catch (error = ›console.error (‘ Error: ’, ошибка))
.then (response = ›console.log (‘ Success: ’, response)); }
оказывать(){
возвращение(
‹Form onSubmit = {this.handleSubmit}›
‹Input type =” text ”name =” name ”onChange = {this.handleChange} /›
‹Input type =” email ”name =” email ”onChange = {this.handleChange} /›
‹Input type =” submit ”value =” Add user ”/› ‹/form›)
}
}