React Native中Animated动画为什么没效果?

轩辕兴敏 阅读 24

我在用React Native的Animated做按钮点击缩放动画,但完全没反应。控制台也没报错,就是点下去啥也不动。我按照文档写了Animated.timing,也用了Animated.View包裹,但就是不生效。

这是我的样式代码:

.button {
  width: 100px;
  height: 50px;
  background-color: #007bff;
  transform: scale(1);
}

是不是不能在样式里直接写transform?还是我漏了什么关键步骤?试过把scale放到Animated.Value里,但还是不行……

我来解答 赞 3 收藏
二维码
手机扫码查看
1 条解答
广云酱~
代码放这了,问题大概率出在 transform 的写法上
Animated.View 的 transform 必须用 Animated.Value 驱动,不能直接在样式里写死 transform: scale(1)
你那样写只是静态样式,动画根本没机会插进去

正确做法是:
1 先创建一个 Animated.Value
2 用 Animated.Value 驱动 transform 数组里的 scale
3 动画目标值也要用 interpolate 或直接传值

看这个最小可运行例子:

import React, { useRef } from 'react';
import { Animated, View, Text, StyleSheet, TouchableOpacity } from 'react-native';

export default function App() {
const scaleValue = useRef(new Animated.Value(1)).current;

const handlePress = () => {
Animated.sequence([
Animated.timing(scaleValue, {
toValue: 0.9,
duration: 100,
useNativeDriver: true,
}),
Animated.timing(scaleValue, {
toValue: 1,
duration: 100,
useNativeDriver: true,
}),
]).start();
};

return (
<View style={styles.container}>
<Animated.View
style={[
styles.button,
{
transform: [{ scale: scaleValue }],
},
]}
>
<Text style={styles.text}>点我</Text>
</Animated.View>
</View>
);
}

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
button: {
width: 100,
height: 50,
backgroundColor: '#007bff',
justifyContent: 'center',
alignItems: 'center',
borderRadius: 8,
},
text: {
color: '#fff',
fontSize: 16,
},
});


注意几个坑:
- transform 必须是数组形式 [{ scale: scaleValue }]
- useNativeDriver: true 要加,不然在 Android 上可能不生效
- 不要在 styles.button 里写 transform: scale(1),否则会覆盖动画值

你把 transform 相关的静态写法删掉,改用上面这种写法,基本就能动了
点赞 1
2026-02-24 21:03