reactjs - 如何在react js中的图像onload事件回调中使用函数?

标签 reactjs

如果我在 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/

相关文章:

javascript - Gatsby 构建后 ScrollMagic 失去功能

javascript - React Native - 导航器和选项卡栏集成

javascript - 如何在 React.createRef() 方法上设置初始值?

javascript - Material UI - 提供给 ButtonBase 的 `component` Prop 无效。请确保 children Prop 在此自定义组件中呈现

javascript - 如何使用 React useState hook 防止竞争条件

javascript - 对 ReactJS 中的 props 更改采取行动

reactjs - React/Redux 中树结构和 shouldComponentUpdate 的性能问题

javascript - 使用map方法在React Native中显示对象数组

css - React Material UI- NativeSelect 下拉菜单样式自定义

javascript - 警告 : Cannot update during an existing state transition (such as within `render` )