实现背景
通常很多时候我们在项目里会用到,进度条这样的交互。为了满足业务的要求、现基于ReactNative开发一款动画进度条,实现方法如下:
// ReactNative AnimatedLine.tsx
import React, { useEffect, useRef, useState } from 'react';
import { Svg, G, Path } from 'react-native-svg';
import { Animated } from 'react-native';
type AnimatedLineProps = {
strokeColor?: string;
value: number;
};
const AnimatedLine: React.FC
/// 初始化路径,参数等
let AnimatedPath = Animated.createAnimatedComponent(Path);
const lineFillAnimation = useRef(new Animated.Value(0));
const [lineAnimation, setLineAnimation] = useState
/// 执行动画
useEffect(() => {
if (lineFillAnimation) {
const _lineAnimation = lineFillAnimation.current.interpolate({
inputRange: [0, 100],
outputRange: [`M5 8 l0 0`, `M5 8 l134 0`],
});
setLineAnimation(_lineAnimation);
}
}, [lineFillAnimation]);
/// 赋值,当有数据了加载
useEffect(() => {
if (!value) return;
/// 清空上次残留值
lineFillAnimation.current.setValue(0);
/// 开始动画
Animated.spring(lineFillAnimation.current, {
toValue: value,
friction: 5,
tension: 20, /// 动画张力
useNativeDriver: true,
}).start();
}, [value]);
return (
);
};
export default AnimatedLine;
效果如图所示:
精彩内容
发表评论