我只是尝试一些简单的事情,比如只在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;
答案 0 :(得分:5)
问题在于您的render
方法。您的onSubmit
事件有自己的上下文,因此当您执行this.handleSubmit
时,您将错误的上下文传递给handleSubmit
。只需绑定this
即可设置!
<form onSubmit={this.handleSubmit.bind(this)}>
或者使用建议的绑定运算符:
<form onSubmit={::this.handleSubmit}>