如何解决通过 forwardRef 传递 useAnimatedGestureHandler
我准备将旧的 React Native Animated 库替换为新的 React Native Reanimated 库以获得性能问题,但我遇到了一个我无法解决的问题。
在我在网上找到的所有示例中,我看到使用 useAnimatedGestureHandler
创建的 GestureHandler 与 Animated.View
位于同一组件中。实际上,这有时是不可能的。
在我之前的应用程序中,我只是通过 forwardRef
将 GestureHandler 对象传递给组件,但似乎 React Native Reanimated 无法做到这一点。我不知道我是语法错误还是只是一个错误。
为了让事情更清晰,我创建了一个 workable Snack,它有 2 个组件 - 一个蓝色框和一个红色框
const App = () => {
const handlerRef = useAnimatedRef();
const y = useSharedValue(0);
handlerRef.current = useAnimatedGestureHandler({
onStart: (_,ctx) => {
ctx.startY = y.value;
},onActive: ({translationX,translationY},ctx) => {
y.value = translationY;
},onEnd: () => {},});
const animatedStyles = useAnimatedStyle(() => ({transform: [{translateY: withSpring(y.value)}]}));
const UsingHandlerDirect = () => (
<PanGestureHandler onGestureEvent={handlerRef.current} >
<Animated.View style={[styles.blueBox,animatedStyles]} />
</PanGestureHandler>
)
const UsingHandlerForwardRef = forwardRef(({animatedStyles},ref) => (
<PanGestureHandler onGestureEvent={ref?.handlerRef?.current}>
<Animated.View style={[styles.redBox,animatedStyles]} />
</PanGestureHandler>
));
return (
<SafeAreaView>
<View style={styles.container}>
<UsingHandlerForwardRef ref={handlerRef} animatedStyles={animatedStyles}/>
<UsingHandlerDirect />
</View>
</SafeAreaView>
);
}
我已将 GestureHandler 保存在 useAnimatedRef handlerRef.current = useAnimatedGestureHandler({})
中,以使事情更具代表性。然后我将 ref 直接传递到 UsingHandlerDirect
组件的 PanGestureHandler。结果是,当我拖动蓝色框时,框将跟随处理程序。所以这个版本有效。
但是一旦我将 handlerRef
传递给 UsingHandlerForwardRef
组件,手势事件就不会被触发。我希望当我拖动红色框时,红色框也会跟随处理程序,但它不会
有人知道是我还是库中的错误吗?
干杯
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。