首页 > 解决方案 > React - 你如何强制 onLoad 调用图像

问题描述

我正在编写一个 React 组件,但无法绕过缓存重新加载图像。我已经用谷歌搜索了其他解决方案,并且知道如果我在它“应该”工作的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回调移至 a 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>
        );
    }
}

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

我也尝试将calculateImageMargin函数放在render()正文中,但由于当时未设置而undefined出现错误。imageRef

标签: javascriptreactjs

解决方案


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


推荐阅读