有没有办法延迟 spring 直到图像加载完毕?

Is there a way to delay a spring until the image has loaded?

我正在使用 react-spring 和 render-props API 来设置背景大小 CSS 属性。只要背景图像发生变化,就会触发变化。问题是:背景图像加载速度并不总是足够快,背景大小无法完美更改。

有没有办法延迟 Spring 直到加载背景图像,或者我是否必须事先预加载所有背景图像?

很多 的背景图片可以设置到我的对象,而且它们的尺寸很大,所以预加载它们可能需要很多 space在内存中,所以它不是我的最佳选择。

这是我的代码:

<Spring native
    from={{backgroundSize: "105%", backgroundImage: streamRectangleBackground}}
    to={{backgroundSize: "101%", backgroundImage: streamRectangleBackground}}
    reset={this.shouldResetAnimation(streamRectangleBackground)}>
    {props =>
        <animated.div className={"streamRectangle"} style={props}>
            <Timer timerSetup={this.state.timerSetup}/>
        </animated.div>
    }
</Spring>

谢谢

我有个想法你可以用在这里。对于 img 组件,有一个 onLoad 事件处理程序。如果您在页面某处显示隐藏了相同 src 的图像。然后你可以设置一个图片加载完成的状态。

然后用这个状态把Spring组件的状态改成属性。像这样:

<img
  style={{display: 'none'}}
  src={streamRectangleBackground}
  onLoad={() => this.setState({loaded: true})}
/>

<Spring native
    from={{backgroundSize: "105%", backgroundImage: streamRectangleBackground}}
    to={{backgroundSize: ${this.state.loaded ? "101%" : "105%"}}}
    reset={this.shouldResetAnimation(streamRectangleBackground)}>
    {props =>
        <animated.div className={"streamRectangle"} style={props}>
            <Timer timerSetup={this.state.timerSetup}/>
        </animated.div>
    }
</Spring>