用react-spring做伸缩动画特效

本文主要讲一下react-spring的用法,顺便说一下如何实现比浏览器规定的最小字体还要小的字体~

在开发中前端经常需要写一些特效,而伸缩特效又是其中较为常见的。但是单纯的伸缩特效又不够有吸引力,很直白,很僵硬。所以我们会采用spring这种弹簧特效,会更加生动。比如说,你要将一个 div 放大到 1.5 倍,spring 在放大过程中会放大到 1.6(你可以自己设定),然后在 1.5 上下波动,逐渐稳定到 1.5。

在 react 中也有一个库,叫 react-spring,一起来看看吧~

react-spring

react-spring引入useSpringanimated

渲染模板部分(return())通过 useSpring 配置参数,加入到 animated.xxx 中,内部是个 icon 和一个图表容器。icon 是随着点击状态改变的,(即点击 ⊕ 的 icon,icon 变成-的 icon,反之同理)

style 里面的transformOrigin属性是要从哪里进行缩放,本例中'right bottom'就是从右下往左上进行缩放。

transform属性实际上就是下面这几行代码的设定了。

1
2
3
4
const [transProps, set] = useSpring(() => ({
scale: 1,
config: { mass: 5, tension: 850, friction: 70 },
}));

这里要注意的是,spring 并不会像我前文举的例子那样,通过参数设定到原来大小的 1.5 或者其他数值,刚刚只是为了便于理解。实际上 spring 设定的三个参数是物理数值,也就是真实的弹簧模型的数值,是不是很神奇~

mass是质量,质量越大,其保持原有运动状态的势能越大;tension是张力,就是使物体改变其原始运动状态(静止)的力的大小;friction是摩擦力,受到的摩擦力越大,能量消耗越快,也就越容易停下来~(哈哈哈,物理知识~)

全文代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import React, { useState } from 'react';
import { useSpring, animated } from 'react-spring';
export const DataMonitor = (props) => {
const trans = (s) => `scale(${s})`;
const [transProps, set] = useSpring(() => ({
scale: 1,
config: { mass: 5, tension: 850, friction: 70 },
}));
const [isZoomed, setZoomState] = useState(props.zoomState);
const typeStr = props.type ? props.type + ' ' : '';
const divClass = 'data-monitor' + typeStr + (isZoomed ? 'zoomed' : '');
const onZoomIn = (e) => {
if (props.onZoomIn) {
props.onZoomIn();
return;
}
setZoomState(!isZoomed);
return set({ scale: 1.5 });
};

const onZoomOut = (e) => {
if (props.onZoomOut) {
props.onZoomOut();
return;
}
setZoomState(!isZoomed);
return set({ scale: 1 });
};
return (
<animated.div
className={divClass}
style={{
transform: transProps.scale.interpolate(trans),
transformOrigin: 'right bottom',
}}
>
<div className="head">
{isZoomed ? (
<span className="zoom" onClick={onZoomOut}>
<img src="/static/img/zoom-out.svg"></img>
</span>
) : (
<span className="zoom" onClick={onZoomIn}>
<img src="/static/img/zoom-in.svg"></img>
</span>
)}
<div className="title">{props.title}</div>
</div>
<div className={'chart-container'}>
<props.chart zoom={isZoomed} {...props.chartProps} />
</div>
</animated.div>
);
};

transform:scale

我们知道浏览器最小的字号是 12px,如果想更小呢?那就可以用 scale 缩放来控制,聪明的你一定想到了~

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2018-2020 Jee
  • Visitors: | Views:

如果您觉得此文章帮助到了您,请作者喝杯咖啡吧~

支付宝
微信