this.state在reactjs组件中为null

时间:2016-03-18 17:32:31

标签: reactjs react-jsx

我只是尝试一些简单的事情,比如只在handleSubmit函数中打印this.state.validForm,但我似乎无法访问this.state.validForm。首先我直接尝试使用此功能,但无济于事。我是新来的反应。

import React, { Component } from 'react';
import TextInput from './TextInput';

class RequestForm extends Component {
    constructor(props) {
        super(props);
        this.state = {validForm : "false"};
        this.getInfoForm = this.getInfoForm.bind(this);
    }

    getInfoForm() {
        return this.state.validForm;
    }

    handleSubmit(event) {
        event.preventDefault();
        console.log('submit values are');
        console.log(event.target.src.value);
        console.log(event.target.email.value);
        console.log(this.state.validForm);
        console.log(this.getInfoForm());
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <TextInput
                    uniqueName="email"
                    name="email"      
                    text="Email Address"
                    required={true}     
                    minCharacters={6}
                    validate="email" 
                    errorMessage="Email is invalid"
                    emptyMessage="Email is required"
                />

                <TextInput 
                    text="User"
                    name="User src"
                    required={true}
                    minCharacters={3}
                    validate="notEmpty"
                    errorMessage="Name is invalid"
                    emptyMessage="Name is required"
                />

                <button type="submit">Submit</button>
            </form>
        );
    }
}

export default RequestForm;

1 个答案:

答案 0 :(得分:5)

问题在于您的render方法。您的onSubmit事件有自己的上下文,因此当您执行this.handleSubmit时,您将错误的上下文传递给handleSubmit。只需绑定this即可设置!

<form onSubmit={this.handleSubmit.bind(this)}>

或者使用建议的绑定运算符:

<form onSubmit={::this.handleSubmit}>