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
相关产品推荐
相关产品推荐

