gpt4 book ai didi

javascript - ReactJS 表单渲染问题

转载 作者:行者123 更新时间:2023-11-30 15:51:52 25 4
gpt4 key购买 nike

我正在学习 reactjs,但我的表单有问题。

当我重新加载我的页面时,我从控制台收到这样的错误 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')
);

这段代码有什么问题?

非常感谢您帮助解决这个问题。

最佳答案

您应该传递对函数 firstnameChangelastnameChange 的引用,但不要调用它们(删除 () 来自他们每个人)

<BasicInput 
label="Firstname"
valChange={ this.firstnameChange }
val={ this.state.firstName }
/>

<BasicInput
label="Lastname"
valChange={ this.lastnameChange }
val={ this.state.lastName }
/>

Example

关于javascript - ReactJS 表单渲染问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39202501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com