首页 > 解决方案 > 我如何循环动画循环进度组件

问题描述

我正在使用 react-native-circular-progress 组件,并且尝试每 30 秒循环一次动画。

即动画长30秒,我希望它在完成后立即重新启动

该组件公开了一个名为 reAnimate 的函数,我在组件安装后立即将其放入 setInterval 函数中。

import React from 'react';
import { StyleSheet, Text, View,Dimensions, Easing } from 'react-native';
import { AnimatedCircularProgress } from 'react-native-circular-progress';

const MAX_POINTS = 30;
export default class App extends React.Component {
    state = {
        isMoving: false,
        pointsDelta: 0,
        points: 1,
    };

    componentDidMount(){

        setInterval(
            () => this.circularProgress.reAnimate(0,100, 30000,Easing.linear),
            30000
        );
    }

    render() {
        const { width } = Dimensions.get("window");
        const window = width - 120;
        const fill = (this.state.points / MAX_POINTS) * 100;
        return (
            <View style={styles.container} >

            <AnimatedCircularProgress
                size={window}
                width={7}
                backgroundWidth={5}
                fill={0}
                tintColor="#ef9837"
                backgroundColor="#3d5875"
                ref={(ref) => this.circularProgress = ref}
                arcSweepAngle={240}
                rotation={240}
                lineCap="round"
            >
                {fill => <Text style={styles.points}>{Math.round((MAX_POINTS * fill) / 100)}</Text>}

            </AnimatedCircularProgress>

            </View>
        );
    }
}

const styles = StyleSheet.create({
    points: {
        textAlign: 'center',
        color: '#ef9837',
        fontSize: 50,
        fontWeight: '100',
    },
    container: {
        flex: 1,
        justifyContent: 'space-between',
        alignItems: 'center',
        backgroundColor: '#0d131d',
        padding: 50,
    },
    pointsDelta: {
        color: '#4c6479',
        fontSize: 50,
        fontWeight: '100',
    },
    pointsDeltaActive: {
        color: '#fff',
    },
});

这是有效的......但是......动画仅在组件安装后30 秒开始。我如何让它立即循环?

任何帮助将不胜感激。

谢谢你。

标签: javascriptreactjstypescriptreact-native

解决方案


原因是 setInterval 不会立即触发,它会在duration你过去 30 分钟后开始,所以你要做的就是在设置间隔之前先打电话,也不要忘记清除间隔。

我会这样做:

componentDidMount(){
  this.circularProgress.animate(100, 30000,Easing.linear);

  this.intervalId = setInterval(
    () => this.circularProgress.reAnimate(0,100, 30000,Easing.linear),
    30000
  );
}

componentWillUnmount() {
  clearInterval(this.intervalId);
}

推荐阅读