反应-如何强制对图像进行onLoad调用

时间:2019-04-14 00:51:52

标签: javascript reactjs

我正在编写一个React组件,无法绕过缓存重新加载图像。我已经用Google搜索了其他解决方案,并且知道如果我将onLoad属性放在src属性之前,则它“应该”起作用,但似乎不起作用。

这是我的代码:

export class ImageComponent extends React.Component {
    render() {
        return (
             <div>
                 <img 
                     onLoad={() => this.props.calculateImageMargin(this.imageRef)}
                     src={"./myImage.jpg"}
                     ref={(ref) => this.imageRef = ref}
                     onClick={() => this.props.openFullScreen()}
                 />
             </div>
        );
    }
}

此图像以这种方式使用:我可以单击将其打开到全屏的图像,然后旋转它。当我保存这些更改时,缩略图应以旋转状态显示它。但是,calculateImageMargin在手动刷新页面时被调用,但是在保存旋转的图像时不被调用。在这种情况下,如何使图像调用onLoad?我曾尝试将onLoad之前的src向上移动,但这似乎不起作用。

编辑

我将onLoad回调移动到了componentDidMount

export class ImageComponent extends React.Component {
    constructor() {
        super();
        this.imageRef = null;
    }

    componentDidMount() {
        this.props.calculateImageMargin(this.imageRef);
    }

    render() {
        return (
             <div>
                 <img 
                     src={"./myImage.jpg"}
                     ref={(ref) => this.imageRef = ref}
                     onClick={() => this.props.openFullScreen()}
                 />
             </div>
        );
    }
}

当我在整个控制台中设置一些控制台日志时,似乎首先由imageRef标记设置了img,然后触发了componentDidMount。但是,适当的图像高度和宽度似乎没有适当地通过。另外,我不确定在我的img函数中修改此解决方案后是否会适当设置calculateImageMargin边距。

我还尝试将calculateImageMargin函数放置在render()主体中,但由于未设置undefined而出现imageRef错误。

1 个答案:

答案 0 :(得分:0)

这里没有足够的代码,或者它按预期工作。图像未重新加载。它只是在旋转。您可能想要的是将onLoad回调移动到render方法的主体,以便在旋转组件并重新渲染时重新计算ImageMargin