如何让react-native-circular-progress动画立即启动并每30秒循环?
解决react-native-circular-progress动画立即启动并循环的问题
你的问题很典型——setInterval会在指定延迟后才第一次执行回调,所以首次动画要等30秒才启动。我们只需要调整一下调用逻辑,让动画在组件挂载时立刻执行一次,之后再按30秒的间隔循环即可。
具体修改步骤:
- 把动画触发逻辑抽成独立函数,方便复用
- 在
componentDidMount中先直接调用一次这个函数,让动画立刻启动 - 启动
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, }; // 抽成独立函数,方便重复调用 startCircularAnimation = () => { this.circularProgress.reAnimate(0, 100, 30000, Easing.linear); }; componentDidMount(){ // 立刻执行一次,启动首次动画 this.startCircularAnimation(); // 之后每30秒循环触发动画 this.intervalId = setInterval(this.startCircularAnimation, 30000); } componentWillUnmount(){ // 清除定时器,避免组件卸载后内存泄漏 clearInterval(this.intervalId); } 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', }, });
逻辑说明:
- 首次手动调用
startCircularAnimation,让动画从组件挂载时立刻开始运行,不需要等待setInterval的30秒延迟 setInterval会在首次动画刚好结束时(30秒后)再次触发动画,完美衔接形成循环- 添加
componentWillUnmount清除定时器是React组件的最佳实践,防止组件卸载后定时器持续运行导致不必要的内存消耗
内容的提问来源于stack exchange,提问作者Paul Bernard
相关产品推荐
相关产品推荐

