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

Expo动画报错Cannot read properties of undefined (reading 'useNativeDriver')求解

修复Expo中Shimmer效果的useNativeDriver错误

错误根源

你的代码里Animated.timing的参数写法存在语法错误:把动画值和配置对象用额外括号包裹,导致配置对象未被正确传入,进而触发useNativeDriver读取undefined的报错。此外还有几处细节问题需要同步修正。

具体修复步骤

  • 修正Animated.timing参数格式
    移除多余的括号,直接传入动画值和配置对象:

    Animated.timing(animatedValue, {
      toValue: 1,
      duration: 1000,
      easing: Easing.linear,
      useNativeDriver: true,
    })
    
  • 补全width变量定义
    代码中使用了width但未声明,通过Dimensions获取屏幕宽度:

    import { Dimensions } from 'react-native';
    const { width } = Dimensions.get('window');
    
  • 为useEffect添加依赖数组
    避免组件重复触发动画,添加空依赖数组确保动画只初始化一次:

    useEffect(() => {
      // 动画逻辑
    }, []);
    
  • 确保LinearGradient正确导入
    在Expo环境中需使用expo-linear-gradient,先安装依赖:

    npx expo install expo-linear-gradient
    

    再导入组件:

    import { LinearGradient } from 'expo-linear-gradient';
    

完整修复后的代码

import React, { useEffect } from 'react';
import { View, StyleSheet, Animated, Easing, Dimensions } from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';

const { width } = Dimensions.get('window');

export default function Shimmer() {
  const AnimatedView = Animated.createAnimatedComponent(LinearGradient);
  const animatedValue = new Animated.Value(0);
  const translateX = animatedValue.interpolate({
    inputRange: [0, 1],
    outputRange: [-width, width],
  });

  useEffect(() => {
    Animated.loop(
      Animated.timing(animatedValue, {
        toValue: 1,
        duration: 1000,
        easing: Easing.linear,
        useNativeDriver: true,
      })
    ).start();
  }, []);

  return (
    <View style={styles.container}>
      <View style={styles.backgroundView}>
        <AnimatedView
          colors={["#a0a0a0", "#b0b0b0", "#b0b0b0", "#a0a0a0"]}
          start={{ x: 0, y: 0 }}
          end={{ x: 1, y: 0 }}
          style={[
            StyleSheet.absoluteFillObject,
            { transform: [{ translateX }] },
          ]}
        />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  backgroundView: {
    width: '100%',
    height: 200,
    backgroundColor: '#f0f0f0',
    overflow: 'hidden',
  },
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 09:24:26