我已使用以下命令在构造函数中注册了processForm
函数:
this.processForm = this.processForm.bind(this);
现在奇怪的是,我的函数识别this.state.Fields
,但在循环内部,它无法识别this
将其视为undefined
。
processForm() {
//validate entire form
var validForm=true;
this.state.Fields.forEach(function(field){
if(field.props.required === "1"){
var validField=(field.props.value != '' && field.props.value != undefined);
if( ! validField) {
if(field.props.name == 'controlLabel') {
this.setState({errControlLabelStyle: '1px solid red'});
} else {
this.setState({errControlLabelStyle: ''});
}
if(field.props.name == 'fieldType') {
this.setState({errFieldTypeStyle: '1px solid red'});
} else {
this.setState({errFieldTypeStyle: ''});
}
}
});
//after validation, data post to server
if (validForm) {
...
}
}
答案 0 :(得分:1)
尝试做这样的事情。发生这种情况是因为你试图打电话给#34;这个"来自回调上下文。
processForm() {
//validate entire form
var that = this;
var validForm=true;
this.state.Fields.forEach(function(field){
if(field.props.required === "1"){
var validField=(field.props.value != '' && field.props.value != undefined);
if( ! validField) {
if(field.props.name == 'controlLabel') {
that.setState({errControlLabelStyle: '1px solid red'});
} else {
that.setState({errControlLabelStyle: ''});
}
if(field.props.name == 'fieldType') {
that.setState({errFieldTypeStyle: '1px solid red'});
} else {
that.setState({errFieldTypeStyle: ''});
}
}
});
//after validation, data post to server
if (validForm) {
...
}
}
答案 1 :(得分:1)
您可以在循环内部使用this
引用,或使用胖箭头ES6语法在循环中保留this
的上下文:
试试这个:
processForm() {
//validate entire form
var validForm=true;
var self = this;
this.state.Fields.forEach(function (field) {
if(field.props.required === "1"){
var validField=(field.props.value != '' && field.props.value != undefined);
if( ! validField) {
if(field.props.name == 'controlLabel') {
self.setState({errControlLabelStyle: '1px solid red'});
} else {
self.setState({errControlLabelStyle: ''});
}
if(field.props.name == 'fieldType') {
self.setState({errFieldTypeStyle: '1px solid red'});
} else {
self.setState({errFieldTypeStyle: ''});
}
}
});
//after validation, data post to server
if (validForm) {
...
}
}
答案 2 :(得分:1)
为避免此类问题导致binding
问题,请始终使用arrow functions
代替callback functions
,请使用以下代码:
processForm() {
//validate entire form
var validForm = true;
this.state.Fields.forEach((field) => {
if(field.props.required === "1"){
var validField = (field.props.value != '' && field.props.value != undefined);
if(!validField){
if(field.props.name == 'controlLabel'){
this.setState({errControlLabelStyle: '1px solid red'});
}else {
this.setState({errControlLabelStyle: ''});
}
if(field.props.name == 'fieldType') {
this.setState({errFieldTypeStyle: '1px solid red'});
}else{
this.setState({errFieldTypeStyle: ''});
}
}
});
//after validation, data post to server
if (validForm) {
...
}
}
注意:问号中的开括号和闭合括号不匹配,因此请确保所有括号都在适当的位置关闭,只需替换使用forEach
循环的行。