如果我在 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);
}
}
};
};
};
关于reactjs - 如何在react js中的图像onload事件回调中使用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62890526/