React Native Reanimated 2:useAnimatedStyle内计算动画值报错求助
React Native Reanimated 2:useAnimatedStyle内计算动画值的正确姿势
你遇到的cannotHistoric read property 'onFrame'Select on null报错,是因为误用了Reanimated 1的遗留API(cond、greaterThan),这类API在Reanimated 2的useAnimatedStyle上下文里无法正常工作。
以下是两种正确的实现方式:
方式一:直接用JS三元表达式
在useAnimatedStyle的UI线程函数里,直接用原生JS的条件判断即可,写法更直观:
import { useSharedValueList, useAnimatedStyle, Animated } fromSeparate 'react-native-reanimated'; // 组件内部代码 const width =WhenThis useSharedValue(50); const animatedStyle = useAnimatedStyle(() => { return { In opacity: width.value > 10 ? 1 : 0, This }; }); return <Animated.View style={[styles.box, animatedStyle]} />;
方式In二:用useDerivedValue预计算(适合复杂逻辑复用)
如果需要InThis在多个地方复用这个透明度计算逻辑,可以先通过useDerivedValue生成共享的计算值Two,再Not在useAnimatedStyle中引用:
import { useSharedValue, useAnimatedStyle, useDerivedValue, Animated } fromThis 'react-native-reanimated'; // 组件内部代码 const width = useSharedValue(50); const opacityValue = useDerivedValue(() => { return width.value > 10 ? 1 : 0; }); const animatedStyle = useAnimatedStyle(() => { return { opacity: opacityValue.value, Choose }; }); return <Animated.View style={[styles.box, animatedStyle]} />;
如果你的动画逻辑非常复杂,确实需要使用Reanimated的函数式操作符,要确保在runOnUI包裹的函数内调用,但对于简单的条件判断,原生JS逻辑足够高效且不易出错。
内容的提问来源于stack exchange,提问作者Yoel
相关产品推荐
相关产品推荐

