Heim > Fragen und Antworten > Hauptteil
P粉2935505752023-08-17 11:02:56
我通过查阅react-native-reanimated
的文档来解决了这个问题。显然,useAnimatedGestureHandler
并没有被弃用,因为它在onDoubleTap
中起作用,更不用说onDrag
在iOS上也正常工作。
但是在处理平移手势的文档中,我找到了这个:
const pan = Gesture.Pan() .onBegin(() => { pressed.value = true; }) .onChange((event) => { offset.value = event.translationX; }) .onFinalize(() => { offset.value = withSpring(0); pressed.value = false; });
所以,不需要从'react-native-gesture-handler'中导入PanGestureHandler
和TapGestureHandler
,也不需要从'react-native-reanimated'中导入useAnimatedGestureHandler
,只需要从'react-native-gesture-handler'中导入Gesture
和GestureDetector
。
Gesture
取代了useAnimatedGestureHandler
,而GestureDetector
取代了PanGestureHandler
和TapGestureHandler
等组件。
我还需要使用useSharedValue()
创建自己的contextX
和contextY
变量,因为据我所知,onBegin()
和onChange()
回调函数没有可设置的上下文。
无论如何,这是修复后的代码,现在在Web和iOS上都完美运行:
import { View, Image } from 'react-native'; import Animated, { useAnimatedStyle, useSharedValue, withSpring, } from 'react-native-reanimated'; import { Gesture, GestureDetector } from 'react-native-gesture-handler'; const AnimatedImage = Animated.createAnimatedComponent(Image); const AnimatedView = Animated.createAnimatedComponent(View); export default function EmojiSticker({ imageSize, stickerSource }) { const scaleImage = useSharedValue(imageSize); const translateX = useSharedValue(0); const translateY = useSharedValue(0); const contextX = useSharedValue(0); const contextY = useSharedValue(0); const onDoubleTap = Gesture.Tap().numberOfTaps(2) .onEnd(() => { if (scaleImage.value !== imageSize * 2) { scaleImage.value = scaleImage.value * 2; } else { scaleImage.value = scaleImage.value / 2; } }); const onDrag = Gesture.Pan() .onBegin(() => { contextX.value = translateX.value; contextY.value = translateY.value; }) .onChange((event) => { translateX.value = event.translationX + contextX.value; translateY.value = event.translationY + contextY.value; }); const imageStyle = useAnimatedStyle(() => { return { width: withSpring(scaleImage.value), height: withSpring(scaleImage.value), }; }); const containerStyle = useAnimatedStyle(() => { return { transform: [ { translateX: translateX.value, }, { translateY: translateY.value, }, ], }; }); return ( <GestureDetector gesture={onDrag}> <AnimatedView style={[containerStyle, { top: -350 }]}> <GestureDetector gesture={onDoubleTap}> <AnimatedImage source={stickerSource} resizeMode="contain" style={[imageStyle, { width: imageSize, height: imageSize }]} /> </GestureDetector> </AnimatedView> </GestureDetector> ); }