简体   繁体   English

如何在功能组件中使用 PanResponder?

[英]How to use PanResponder in functional components?

The official documentation and all the tutorials I found use PanResponder as a part of React Classes, but is there a way we can use it with functional components and hooks?我发现的官方文档和所有教程都使用 PanResponder 作为 React Classes 的一部分,但是有没有办法可以将它与功能组件和钩子一起使用? I tried doing it as follows but it doesn't seem to work:-我尝试按以下方式进行操作,但似乎不起作用:-

const App = props => {
  const position = useRef(new Animated.ValueXY()).current;
  const panResponder = useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: (evt, gestureState) => true,
      onPanResponderMove: (evt, gestureState) => {
        position.setValue({x: gestureState.dx, y: gestureState.dy});
      },
      onPanResponderRelease: (evt, gestureState) => {},
    }),
  ).current;

...

<Animated.View
            {...panResponder.panHandlers}
            style={[
              {transform: position.getTranslateTransform()},
              styles.appStyles,
            ]}>
...
</Animated.View>

found solution here: https://github.com/facebook/react-native/issues/25360#issuecomment-505241400在这里找到解决方案: https://github.com/facebook/react-native/issues/25360#issuecomment-505241400

useMemo avoids recreating the PanResponder on every rerendering useMemo 避免在每次重新渲染时重新创建 PanResponder

then your code should look like this那么你的代码应该是这样的

const App = props => {
  const position = useRef(new Animated.ValueXY()).current;
  const panResponder = React.useMemo(() => PanResponder.create({
      onStartShouldSetPanResponder: (evt, gestureState) => true,
      onPanResponderMove: (evt, gestureState) => {
        position.setValue({x: gestureState.dx, y: gestureState.dy});
      },
      onPanResponderRelease: (evt, gestureState) => {},
    }), []);

...

<Animated.View
            {...panResponder.panHandlers}
            style={[
              {transform: position.getTranslateTransform()},
              styles.appStyles,
            ]}>
...
</Animated.View>

The official doc suggests using useRef()官方文档建议使用useRef()

https://reactnative.dev/docs/panresponder https://reactnative.dev/docs/panresponder

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM