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

使用Reanimated 2的useAnimatedKeyboard()热重载崩溃求助

Expo中Reanimated 2 useAnimatedKeyboard热重载崩溃问题解决

问题复现

在Expo新项目中使用Reanimated 2的useAnimatedKeyboard() Hook,代码完全遵循官方文档编写,初始运行正常,但按下r键触发热重载时,Android和iOS端均出现崩溃。代码示例如下:

function AnimatedKeyboardExample() {
    const keyboard = useAnimatedKeyboard();
    const translateStyle = useAnimatedStyle(() => {
        return {
            transform: [{ translateY: -keyboard.height.value }],
        };
    });

    return (
        <ScrollView contentContainerStyle={{flex: 1, justifyContent: 'center', alignItems: 'center' }}>
            <Animated.View style={translateStyle}>
                <TextInput />
            </Animated.View>
        </ScrollView>
    );
}

解决方案

这个问题是Reanimated 2早期版本的已知热重载兼容性问题,可通过以下方式解决:

  • 优先方案:升级依赖版本
    将react-native-reanimated升级到2.4.0及以上版本,官方已在该版本修复了useAnimatedKeyboard的热重载崩溃问题。执行命令更新:

    expo install react-native-reanimated@latest
    
  • 临时兼容方案(无法升级时使用)
    通过useSharedValue手动同步键盘高度,避免直接在useAnimatedStyle中引用keyboard.height:

    import { useAnimatedKeyboard, useAnimatedStyle, useSharedValue } from 'react-native-reanimated';
    import { useEffect } from 'react';
    import { ScrollView, TextInput } from 'react-native';
    
    function AnimatedKeyboardExample() {
      const keyboard = useAnimatedKeyboard();
      const keyboardHeight = useSharedValue(0);
    
      useEffect(() => {
        // 订阅键盘高度变化,同步到shared value
        const subscription = keyboard.addListener((event) => {
          keyboardHeight.value = event.height;
        });
    
        return () => subscription.remove();
      }, [keyboard]);
    
      const translateStyle = useAnimatedStyle(() => {
        return {
          transform: [{ translateY: -keyboardHeight.value }],
        };
      });
    
      return (
        <ScrollView contentContainerStyle={{flex: 1, justifyContent: 'center', alignItems: 'center' }}>
          <Animated.View style={translateStyle}>
            <TextInput />
          </Animated.View>
        </ScrollView>
      );
    }
    

补充说明

热重载时Reanimated的JSI绑定会重置,早期版本中直接引用keyboard.height.value会导致无效引用触发崩溃,通过useSharedValue中转后,能避免该问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 05:03:36