为什么我的表单输入没有获取任何信息?

时间:2018-05-23 20:04:59

标签: javascript forms reactjs input ecmascript-6

我正在使用React来创建表单。当我尝试键入其中一个表单时没有任何反应。在React dev工具中,每个输入的状态一次只能接收一个字母。当我输入时我在控制台.log e.target时,它没有更新输入的值。

我不确定我做错了什么。有什么想法吗?

这是我的代码:

import React, {Component} from "react";
import Form from "./Form";
import Badge from "./Badge";

class App extends Component {
    constructor(){
        super();

        this.state = {
            data: [],
            inputs: {
                firstName: "",
                lastName: "",
                email: "",
                birth: "",
                phone: "",
                favFood: "",
                bio: ""
            }

        }
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);

    }

    handleChange(e){
        const {name, value} = e.target;
        console.log(e.target);
        this.setState({
            [name]: value
        })
    }

    handleSubmit(e){
        e.preventDefault();
        this.setState(prevState => {
            return{
                data: [
                    ...prevState.data,
                    this.state.inputs
                ],

                firstName: "",
                lastName: "",
                email: "",
                birth: "",
                phone: "",
                favFood: "",
                bio: ""
            }
        })
    }

    render(){
        return(
            <div>
                <Form inputChange={this.handleChange}
                submitForm={this.handleSubmit} 
                fName={this.state.inputs.firstName} 
                lName={this.state.inputs.lastName} 
                email={this.state.inputs.email} 
                birth={this.state.inputs.birth} 
                phone={this.state.inputs.phone} 
                favFood={this.state.inputs.favFood} 
                bio={this.state.inputs.bio}/>
            </div>
        )
    }  
}

export default App;

2 个答案:

答案 0 :(得分:0)

当您setState更新表单模型时,您没有达到正确的级别。您需要将其更改为:

        this.setState(prevState => {
        return{
            data: [
                ...prevState.data,
                this.state.inputs
            ],

            inputs: {
              firstName: "",
              lastName: "",
              email: "",
              birth: "",
              phone: "",
              favFood: "",
              bio: ""
            }
        }
    })

答案 1 :(得分:0)

Your handleChange is not correct, you are setting value for each variable but you are referencing to it as object inside input ex, this.state.inputs.firstName

let inputs = Object.assign({}, this.state.inputs);    //create copy of object
inputs.firstName = 'JohnDoe';                        //update value
this.setState({inputs});