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

React Native圆形循环缩放动画求助:停留及缩小逻辑实现问题

React Native Reanimated 实现圆形放大-停留-缩小无限循环动画

你当前的代码仅实现了放大的循环逻辑,缺少最大尺寸停留和缩小回原尺寸的关键环节。要完成完整的动画流程,需要通过withSequence将「放大→停留→缩小」三个阶段按顺序串联,再配合withRepeat实现无限循环。

修改后的完整代码

import React, { FunctionComponent, useEffect } from 'react';
import Animated, {
    useAnimatedStyle,
    useSharedValue,
    withRepeat,
    withSequence,
    withTiming,
} from 'react-native-reanimated';
import styled from 'styled-components/native';

type Props = {};

const CircleAnimation: FunctionComponent<Props> = () => {
    const widthAndHeight = useSharedValue(50);
    const stageDuration = 2000; // 单个动画阶段时长(毫秒)

    const foregroundCircleStyle = useAnimatedStyle(() => {
        return {
            width: widthAndHeight.value,
            height: widthAndHeight.value,
            borderRadius: widthAndHeight.value / 2,
        };
    });

    useEffect(() => {
        // 串联完整动画流程并设置无限循环
        widthAndHeight.value = withRepeat(
            withSequence(
                // 阶段1:2秒内从50px放大到100px
                withTiming(100, { duration: stageDuration }),
                // 阶段2:保持100px状态2秒(目标值与当前值一致时,动画会维持状态)
                withTiming(100, { duration: stageDuration }),
                // 阶段3:2秒内从100px缩小回50px
                withTiming(50, { duration: stageDuration })
            ),
            -1, // -1代表无限重复
            false // 不启用反向播放
        );
    }, [stageDuration, widthAndHeight]);

    return <ForegroundCircle style={[foregroundCircleStyle]} />;
};

const ForegroundCircle = styled(Animated.View)`
    width: 50px;
    height: 50px;
    border-radius: 25px;
    background-color: yellow;
`;

export default CircleAnimation;

核心修改说明

  • withSequence串联阶段:该API会严格按传入顺序执行动画,前一阶段完成后才启动下一阶段,完美匹配线性的「放大→停留→缩小」流程。
  • 停留阶段实现:通过withTiming设置与当前值相同的目标值,同时指定停留时长,即可实现保持尺寸的效果。
  • 移除冗余的withDelay:动画序列本身已包含各阶段的时长控制,无需额外添加延迟。
  • 统一时长变量:将原有的秒级duration改为毫秒级stageDuration,避免单位转换错误,语义更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:05:19