React Native 动画Animated

发布于:2025-07-13 ⋅ 阅读:(15) ⋅ 点赞:(0)

一、基础动画

1)new Animated.Value(xx):实例化一个初始值
2)Animated.timing({xxx}):创建动画 .start()启动

// 点击按钮,box向右移动

// 动画初始值
const marginLeft = useRef(new Animated.Value(0)).current;

// ...
<Button title='按钮' onPress={() => {
     Animated.timing(marginLeft, {
         toValue: 300, // 目标值
         duration: 500, // 持续时间毫秒
         useNativeDriver: false, // 是否启用原生驱动
     }).start();
 }} />

<Animated.View
    style={[
        styles.view,
        {marginLeft: marginLeft}
    ]}
/>

二、transform动画

// 点击按钮,box旋转
const rotate = useRef(new Animated.Value(0)).current;

// roate值是需要单位的, rotate.interpolate就是把输入值(没有单位)映射为输出值(有单位)
const rotateValue = rotate.interpolate({
   inputRange: [0, 90], // 输入值
   outputRange: ['0deg', '90deg'], // 输出值
})

// ...

<Button title='按钮' onPress={() => {
     Animated.timing(rotate, {
         toValue: 90,
         duration: 1000,
         useNativeDriver: false,
     }).start();
 }} />

 <Animated.View
     style={[
         styles.view,
         {transform: [
             { rotate: rotateValue }
         ]}
     ]}
 />
// 点击按钮,box放大

const scale = useRef(new Animated.Value(1)).current;
// ...

<Button title='按钮' onPress={() => {
   Animated.timing(scale, {
        toValue: 1.5, // 0.x 缩小
        duration: 1000,
        useNativeDriver: false,
    }).start();
}} />

<Animated.View
    style={[
        styles.view,
        {transform: [
            { scale: scale }
        ]}
    ]}
/>

三、渐变动画

// 点击按钮,box透明度0到1
const opacity = useRef(new Animated.Value(0)).current;

// ...
<Button title='按钮' onPress={() => {
     Animated.timing(opacity, {
         toValue: 1,
         duration: 1000,
         useNativeDriver: false,
     }).start();
 }} />

 <Animated.View
     style={[
         styles.view,
         {opacity: opacity}
     ]}
 />

四、布局动画LayoutAnimation

// 点击按钮,box显示

const [showView, setShowView] = useState(false)

// ...

<Button title='按钮' onPress={() => {           
    LayoutAnimation.configureNext(
        LayoutAnimation.Presets.linear
        // 或 LayoutAnimation.Presets.spring
        // 或LayoutAnimation.Presets.easeInEaseOut,
        () => {
           console.log('动画结束');
        },
        () => {
            console.log('动画异常');
        }
    )

	// 简写
	// LayoutAnimation.linear();
    // LayoutAnimation.spring();
    // LayoutAnimation.easeInEaseOut();


    setShowView(true);
}} />

{showView && <View style={styles.view} />}


网站公告

今日签到

点亮在社区的每一天
去签到