React Native使用Animated同时设置translateX和translateY时转换失败的问题求助
React Native使用Animated同时设置translateX和translateY时转换失败的问题求助
嘿,我刚踩过这个坑!你看报错提示里明确说了“You must specify exactly one property per transform object”,问题就出在你写transform样式的方式上。
你原来的代码里把translateY和translateX放在了同一个transform对象里:
transform: [{ translateY: bounceValue, translateX: shakeValue }]
但React Native的Animated(尤其是开启useNativeDriver: true的时候)要求每个变换属性都得是独立的对象,因为原生端的CATransform3D不支持在单个变换条目里同时设置多个属性。
只需要把transform数组拆成两个对象就搞定了,修正后的完整代码如下:
const BounceInUp: FC = ({ children, teddyBear }) => { const bounceValue = new Animated.Value(120); const shakeValue = new Animated.Value(0); const animate = useCallback(() => { Animated.sequence([ Animated.delay(300), Animated.spring(bounceValue, { useNativeDriver: true, toValue: -10, velocity: 3, friction: 8, }), Animated.sequence([ Animated.timing(shakeValue, { toValue: 10, duration: 100, useNativeDriver: true }), Animated.timing(shakeValue, { toValue: -10, duration: 100, useNativeDriver: true }), Animated.timing(shakeValue, { toValue: 10, duration: 100, useNativeDriver: true }), Animated.timing(shakeValue, { toValue: 0, duration: 100, useNativeDriver: true }), ]), ]).start(); }, [bounceValue, shakeValue]); useEffect(() => { animate(); }, [teddyBear.id]); return ( <Animated.View style={[ styles.subView, { transform: [ { translateY: bounceValue }, { translateX: shakeValue } ] } ]} > {children} </Animated.View> ); };
简单来说,就是把原来的单个transform对象拆成两个,分别对应translateY和translateX,这样原生驱动就能正确解析成CATransform3D了,报错就会消失啦!
备注:内容来源于stack exchange,提问作者for connection
相关产品推荐
相关产品推荐

