javascript - 选择照片后如何显示错误消息?

标签 javascript reactjs

我的组件 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/

相关文章:

javascript - 在浏览器中调试reducer时,为什么看不到变量的值?

javascript - ReactJS:将数据从 child 传递给 parent

reactjs - 为什么 jsx 中的三元运算符不起作用

javascript - 未捕获的类型错误 : Cannot read property 'keys' of undefined

javascript - Node.js module.exports 通过接口(interface)

reactjs - 为什么console.log 在react js 中记录两次?

javascript - 在 React 组件之外访问 Redux Store 会返回初始值

javascript - Reactjs 仪表板 - 具有一组参数的多个实例

javascript - 如何防止在浏览器外触发onmouseleave事件?

javascript - 使用 CSS 隐藏输入后,文本输入框的自动完成下拉列表仍然存在