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

React Native新手求助:如何用react-native-reanimated实现点从Y到X移动?

实现React Native Reanimated点的往返移动

两种常见实现方式:


1. 自动往返动画(无限循环)

使用withRepeat包裹基础动画,开启反向播放即可实现自动来回移动:

import React, { useEffect } from 'react';
import { View, StyleSheet } from 'react-native';
import Animated, { useSharedValue, useAnimatedStyle, withTiming, withRepeat } from 'react-native-reanimated';

export default function App() {
  // 记录点的位置,初始在X点(这里设为0)
  const dotPosition = useSharedValue(0);

  useEffect(() => {
    // withRepeat参数:动画函数、重复次数(-1=无限)、是否反向播放
    dotPosition.value = withRepeat(
      withTiming(100, { duration: 1500 }), // 从0到100(Y点)的动画
      -1,
      true
    );
  }, []);

  const animatedDotStyle = useAnimatedStyle(() => {
    return {
      transform: [{ translateX: dotPosition.value }],
    };
  });

  return (
    <View style={styles.container}>
      <Animated.View style={[styles.dot, animatedDotStyle]} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  dot: {
    width: 20,
    height: 20,
    borderRadius: 10,
    backgroundColor: 'blue',
  },
});

2. 手动触发往返(点击切换)

通过按钮控制动画目标位置,实现点击从X到Y,再点击从Y到X:

import React from 'react';
import { View, StyleSheet, Button } from 'react-native';
import Animated, { useSharedValue, useAnimatedStyle, withTiming } from 'react-native-reanimated';

export default function App() {
  // 标记当前是否在X点
  const isAtX = useSharedValue(true);
  // 记录点的目标位置
  const dotPosition = useSharedValue(0);

  const toggleMove = () => {
    // 切换位置状态
    isAtX.value = !isAtX.value;
    // 更新目标位置,触发动画
    dotPosition.value = withTiming(
      isAtX.value ? 0 : 100, // 在X就去Y,在Y就回X
      { duration: 1500 }
    );
  };

  const animatedDotStyle = useAnimatedStyle(() => {
    return {
      transform: [{ translateX: dotPosition.value }],
    };
  });

  return (
    <View style={styles.container}>
      <Button title="切换位置" onPress={toggleMove} />
      <Animated.View style={[styles.dot, animatedDotStyle]} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    gap: 20,
  },
  dot: {
    width: 20,
    height: 20,
    borderRadius: 10,
    backgroundColor: 'blue',
  },
});

关键说明:

  • withRepeat的reverse参数是实现自动往返的核心,设为true动画会在完成后反向执行
  • 手动切换的核心是用共享值记录当前位置状态,点击时更新目标位置,Reanimated会自动处理过渡动画

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 23:04:57