首页 > 解决方案 > 如何在缩放功能中的 2 个比例之间进行动画反应?

问题描述

当我的状态发生变化时,我想转换。我目前的结果是我的整个组件在缩放期间重新加载,我想要更平滑的缩放。我怎样才能做到这一点?

我使用 react-tappable 来检测夹点。

这是我的功能:

// Zoom on pinch until maxScale, else resize to initial scale
handlePinchStart = () => {
const { scale, maxScale } = this.state;
if (scale <= maxScale) {
  this.setState(state => ({ scale: state.scale + 0.5 }));
} else {
  this.resize();
 }
}

标签: javascriptreactjsanimationscale

解决方案


您可以向要放大或缩小的元素添加或删除 CSS 类,并根据您的状态执行此操作。例如,

return (
   <div className={scale <= maxScale ? "my-element zoom-in" : "my-element"}>My Element</div>
)

它只是说,如果您的缩放状态小于或等于 maxScale,则将元素的 className 设为my-element zoom-in,否则将其设为my-element。而在 CSS 中,这些类可以是这样的:

.my-element {
   /* Some stylings for your element */
   transition: transform 0.5s;
}

.my-element.zoom-in {
   transform: scale(2);
}

只要您的缩放状态是 <= maxScale,您的元素就会附加.zoom-in CSS 类。而.zoom-in类只会让元素的比例翻倍。并且由于放入transition: transform 0.5s;了您实际元素的类(.my-element),它会平稳增长,当比例大于 myScale 时,.zoom-in类将被删除,您的元素将只有.my-element类,并且缩小顺利恢复到原来的大小。


推荐阅读