Reanimated中useAnimatedStyle不生效是怎么回事?

小玉娟 阅读 43

我在用React Native的Reanimated做动画,写了个useAnimatedStyle想控制一个View的translateY,但完全没反应。试过把sharedValue的值直接写死也不动,是不是哪里漏了?

代码大概是这样:

const translateY = useSharedValue(0);
const animatedStyle = useAnimatedStyle(() => {
  return {
    transform: [{ translateY: translateY.value }]
  };
});
// 然后在JSX里用了 <Animated.View style={[styles.box, animatedStyle]} />
我来解答 赞 15 收藏
二维码
手机扫码查看
1 条解答
上官清梅
这种情况大概率是漏了babel配置,Reanimated 2+需要在babel.config.js里加上插件才能正常工作。

打开项目根目录的babel.config.js,在plugins数组里加上'react-native-reanimated/plugin',注意顺序很重要,这个插件要放在最后面:

module.exports = {
presets: ['module:@react-native/babel-preset'],
plugins: ['react-native-reanimated/plugin'], // 放最后
};


配完以后记得清一下缓存,重启packager:

npx react-native start --reset-cache
# 或者
npx expo start --clear


另一个容易踩的坑是Animated.View的导入来源。有些人可能从react-native导入了Animated.View,那样是带不了animatedStyle的。必须从react-native-reanimated导:

import Animated from 'react-native-reanimated';
// 用 Animated.View 而不是从 react-native 导入的那个


如果上面两个都确认没问题,那检查一下是不是在主线程之外调用了sharedValue的修改方法——比如在setTimeout、Promise这些回调里直接改translateY.value是不行的,得用runOnJS或者在UI线程执行。
点赞
2026-03-17 06:02