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

古纳·谢卡(Guna Shekar)

我发现的官方文档和所有教程都将PanResponder用作React Classes的一部分,但是有没有办法将其与功能组件和挂钩一起使用?我尝试这样做,但似乎不起作用:-

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>
Manu Rauck

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

useMemo避免在每次重新渲染时重新创建PanResponder

那么你的代码应该看起来像这样

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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在功能组件中使用类组件功能

如何在功能组件中使用 componentWillReceiveProps

如何在功能组件中使用 componentDidMount() 来执行功能

如何在Reactjs功能组件history.push中使用

如何在功能组件中使用插件的指令-Vue 2

如何在React功能组件中使用动画SVG?

如何在功能组件 React 中使用 setState?

如何在功能组件的映射中使用React refs?

如何在功能组件中使用 {...this.props}

如何在 React Native 的功能组件中使用 forwardRef?

如何在功能组件的select标记中使用defaultValue?

如何在功能组件中使用setNativeProps?反应本机

如何在功能组件(摄影机)中使用ref

如何在反应功能组件中使用 history.push?

如何在反应中使用功能组件单击按钮时显示组件

如何在React Native中使用功能组件的方法到类组件中?

如何在功能组件和挂钩中使用AppState?必要还是我使用useEffect错误?

如何在Typescript中使用Form.create并与功能组件配合使用

如何在功能组件中使用 react-datepicker 的 excludeTimes 并使用 onChange?

如何在子组件上禁用PanResponder-React Native

如何在返回 TypeScript 中 ReactNative 功能组件的高阶函数中使用钩子?

任何能够解释目标属性如何在此功能组件中使用的人

如何在Android中没有活动和片段的功能中使用布局组件?

如何在功能组件中使用React Typescript键入任何参数

我该如何在React中使用Typescript声明无状态功能组件?

如何在功能组件中使用onChange事件处理程序动态设置状态

如何在功能组件的React中的props中使用泛型?

如何在React中使用带有箭头功能的嵌套组件定义为常量?

如何在TypeScript中使用带有React无状态功能组件的子级?