我正在学习反应,我的表格有问题。
当我重新加载页面时,我从我的控制台收到错误profile.js:54 Uncaught TypeError: Cannot read property 'target' of undefined
。表单不会在我的页面中呈现,但我认为此代码应该可以正常工作。
我的档案profile.js:
var BasicInput = React.createClass({
render: function () {
return (
<input type="text" onChange={this.props.valChange} value={ this.props.val} />
);
}
});
var BasicForm = React.createClass({
getInitialState: function(){
return {
firstName: '',
lastName: ''
};
},
submit: function (e){
var self;
e.preventDefault()
self = this;
console.log(this.state);
var data = {
firstName: this.state.firstName,
lastName: this.state.lastName
};
// Submit form via jQuery/AJAX
$.ajax({
type: 'POST',
url: '/accounts/profile/details-form',
data: data
})
.done(function(data) {
self.clearForm()
})
.fail(function(jqXhr) {
console.log('failed to change basic info');
});
},
clearForm: function() {
this.setState({
firstName: "",
lastName: ""
});
},
firstnameChange: function(e){
this.setState({firstName: e.target.value});
},
lastnameChange: function(e){
this.setState({lastName: e.target.value});
},
render: function() {
return (
<form onSubmit={this.submit}>
<div className="form-half">
<BasicInput label="Firstname" valChange={this.firstnameChange()} val={this.state.firstName}/>
</div>
<div className="form-half">
<BasicInput label="Lastname" valChange={this.lastnameChange()} val={this.state.lastName}/>
</div>
<button type="submit">Submit</button>
</form>
);
}
});
ReactDOM.render(
<BasicForm />,
document.getElementById('basicInfoForm')
);
此代码有什么问题?
非常感谢您对此问题的帮助。
答案 0 :(得分:2)
您应该将参考传递给函数firstnameChange
和lastnameChange
,而不是调用它们(从每个中移除()
)
<BasicInput
label="Firstname"
valChange={ this.firstnameChange }
val={ this.state.firstName }
/>
<BasicInput
label="Lastname"
valChange={ this.lastnameChange }
val={ this.state.lastName }
/>