You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在react-native-countdown-circle-timer中实现双计时器无限交替运行

解决方案

不能直接在单个CountdownCircleTimer组件的duration属性中配置两个不同时长,该属性仅支持传入单个数字,用于定义当前单次倒计时的总时长。

要实现双计时器无限循环的效果,你可以通过新增状态标记当前运行的计时器序号,提前定义两套计时器配置,在倒计时结束的回调中切换序号触发组件重新初始化即可,修改后的完整代码如下:

import * as React from 'react';
import { Text, View, StyleSheet, Animated, Button } from 'react-native';
import Constants from 'expo-constants';
import { CountdownCircleTimer } from 'react-native-countdown-circle-timer';

// 定义两套计时器配置,可自行修改时长、颜色参数
const timerConfigs = [
  {
    duration: 10,
    color: '#FFFF00'
  },
  {
    duration: 15, // 第二个计时器的时长
    color: '#0000ff' // 第二个计时器的颜色
  }
]

export default function App() {
  const [isPlaying, setIsPlaying] = React.useState(true)
  // 标记当前运行的计时器序号,0为第一个,1为第二个
  const [currentTimerIndex, setCurrentTimerIndex] = React.useState(0)
  const currentConfig = timerConfigs[currentTimerIndex]

  return (
    <View style={styles.container}>
      <CountdownCircleTimer
        // key变更时组件会重新初始化,加载新的时长、颜色配置
        key={currentTimerIndex}
        isPlaying={isPlaying}
        duration={currentConfig.duration}
        colors={[[currentConfig.color, 1]]}
        onComplete={() => {
          // 切换计时器序号
          setCurrentTimerIndex(prev => prev === 0 ? 1 : 0)
          // 返回true让新的计时器自动开始运行
          return [true]
        }}
    >
      {({ remainingTime, animatedColor }) => (
        <Animated.Text style={{ color: animatedColor, fontSize: 40 }}>
          {remainingTime}
        </Animated.Text>
      )}
    </CountdownCircleTimer>
    <Button title="Toggle Playing" onPress={() => setIsPlaying(prev => !prev)}/>
  </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  }
});

内容的提问来源于stack exchange,提问作者Caquibf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:18:03