我的组件 InputAvatar 有问题 - https://codesandbox.io/s/721n5346x6
如果照片尺寸不是 200x200 像素,我如何在选择照片后显示错误消息?
我认为问题出在img.onload = function(),因为没有及时返回错误信息。
提前致谢
最佳答案
你是对的,onload
没有及时返回。这是一个异步事件回调,因此它仅在图像加载完成后触发。这会导致从 getErrors
返回一个空数组值,因为它在图像加载之前执行。
为了使代码工作,您必须引入一些异步感知代码,例如。使用 promise 。
getErrors(value = this.state.file || "") {
// Return a single promise and move the function execution inside.
return new Promise((resolve, reject) => {
const errors = []
const img = new Image();
img.src = value;
img.onload = function() {
var w = img.width;
var h = img.height;
errors.push("error");
if (w != 200 || h != 200) {
errors.push("The photo must be 200 x 200 px.");
}
// Resolve the pending promise with the errors value letting callers know it's ready.
resolve(errors)
};
})
}
这样您就可以等待图像加载的结果并以您需要的方式使用它。
validate(value = this.state.file || "") {
this.getErrors(value)
// Wait for the errors and only then set the state.
.then(errors =>
this.setState({
errors
});
)
}
关于javascript - 选择照片后如何显示错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54607165/