React form表单fetch提交数据

import React, { Component } from 'react'

class PostFrom extends Component {
    constructor(props) {
        super(props)
        this.state = {
            title: '',
            body: ''
        };
        // this.onChange = this.onChange.bind(this)
    }
    onChange(e) {//把当前修改的值赋入state
        this.setState({
            [e.target.name]:e.target.value
        })
    }
    onSubmit(e) {
        // 阻止事件传递
       e.preventDefault();
        // 把表单用的最终数据从state中提取出来,传入请求
        const post ={
            title:this.state.title,
            body:this.state.body
        }
        fetch('http://jsonplaceholder.typicode.com/posts',{
            // post提交
            method:"POST",
            headers:{
                "Content-type":"application/json"
            },
            body:JSON.stringify(post)//把提交的内容转字符串
        })
        .then(res =>res.json())
        .then(data =>{
            console.log(data)
        })
    }
    render() {
        return (
            

添加内容




) } } export default PostFrom;

 

你可能感兴趣的:(React)