当我在映射方法中调用onChange函数时,我得到了以下错误
Uncaught TypeError: Cannot read property 'onCheckChange' of undefined at onChange
我的代码在之后
getPlanCheckbox(jsonParseservicelist, bbuserid) {
const returnresult = jsonParseservicelist.map(function (single) {
return (
<div className="">
<label className="" >
<input type="checkbox" onChange={() => this.onCheckChange(bbuserid, single.plantype)} defaultChecked={single.isActive == 1 ? "checked" : ""} />
<span className="" />
</label>
</div>);
});
return returnresult;
}
onCheckChange = (e, bbuid, plantype) => {
console.log(bbuid, plantype);
}
我尝试了一下,发现了2个解决方案
第一个刚刚用以下取代了您的功能
getPlanCheckbox(jsonParseservicelist, bbuserid) {
var self = this;
const returnresult = jsonParseservicelist.map(function (single) {
return (
<div className="">
<label className="" >
<input type="checkbox" onChange={() => self.onCheckChange(bbuserid, single.plantype)} defaultChecked={single.isActive == 1 ? "checked" : ""} />
<span className="" />
</label>
</div>);
});
return returnresult;
}
只需将this
放入另一个variable
和该变量名的用户中即可调用函数比方说
var self = this;
现在我用self调用类似的函数
self.onCheckChange();
第二种是使用地图作为箭头函数
data.map((single) => {
})
将映射函数定义为箭头,因为从其他方面来看,this
不会是全局上下文。如果您还没有在构造函数中绑定this
,那么getPlanCheckbox
函数也是如此
getPlanCheckbox = (jsonParseservicelist, bbuserid) => {
const returnresult = jsonParseservicelist.map((single) => {
return (
<div className="">
<label className="" >
<input type="checkbox" onChange={() => this.onCheckChange(bbuserid, single.plantype)} defaultChecked={single.isActive == 1 ? "checked" : ""} />
<span className="" />
</label>
</div>);
});
return returnresult;
}