如何在react js中使用回调image onload事件的函数



如果我在image.onload回调中使用了setState或任何其他函数,那么我会得到类似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);
}
}
};
};
};

最新更新