为什么我不能在React中调用此函数?

时间:2018-07-01 10:54:44

标签: javascript reactjs

我收到错误消息:“ TypeError:this.createCanvas不是函数”。

我不明白为什么。我已经将其绑定在构造函数中。

import React, { Component } from 'react';

class ImageEditor extends Component {

constructor() {
    super();
    this.createCanvas = this.createCanvas.bind(this);
    this.getImageDimensions = this.getImageDimensions.bind(this);
}

componentDidMount() {
    const imageurl = "https://storage.googleapis.com/" + this.props.location.state.imageuri;
    this.getImageDimensions(imageurl);
}

getImageDimensions(url) {
    var img = new Image();

    img.onload = function() {
        this.createCanvas(this.width, this.height);
    }

    img.src = url;
}

createCanvas(width, height) {
    let mycanvas = document.createElement("canvas");
    mycanvas.width = width;
    mycanvas.height = height;
    mycanvas.id = "mycanvas";
    document.body.appendChild(mycanvas);
}

render() {
    return (
        <h1>{this.imageurl}</h1>
    )
}

}

导出默认的ImageEditor;

1 个答案:

答案 0 :(得分:0)

您的img.onload也必须具有箭头功能,否则this将不是您想要的。您可以了解有关here为何会出现这种情况的更多信息。

img.onload = () => {
    this.createCanvas(img.width, img.height);
}