如果我setState
在image.onload
回调中使用了其他函数或其他函数,则出现类似的错误this is not function
。如果我使用局部变量来处理错误,则会在之前更新局部变量的值之前检查条件image.onload
。
handleProductImage = (e) => {
let file = e.target.files[0];
let reader = new FileReader();
let height, width, isError = false;
reader.readAsDataURL(file);
reader.onload = function (file) {
let img = new Image();
img.src = file.target.result;
img.onload = function () {
height = this.height;
width = this.width;
if (height && width) {
if (height < 250 || width < 250) {
//--Use local variable---//
//isError = true;
//---Use setState for handle error---//
// this.setState({ isError: true });
//---Call function directly---//
this.props.setErrorMessage();
}
else {
//--Use local variable---//
//isError = false;
//---Use setState for handle error---//
// this.setState({ isError: false });
//---Call function directly---//
this.handleImageCropper(e)
}
}
}
}
//Use local variable for function call
//if (isError) {
//console.log("error");
//this.props.setErrorMessage();
//}
//else {
//this.handleImageCropper(e)
//}
}
您使用this
并有时假定它是图像,但后来假定它是组件。请尝试以下操作:
handleProductImage = (e) => {
const me = this;
let file = e.target.files[0];
let reader = new FileReader();
let height,
width,
isError = false;
reader.readAsDataURL(file);
reader.onload = function (file) {
let img = new Image();
img.src = file.target.result;
img.onload = function () {
height = this.height;//leave "this" if you mean img.height
width = this.width;
if (height && width) {
if (height < 250 || width < 250) {
me.props.setErrorMessage();
} else {
me.handleImageCropper(e);
}
}
};
};
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句