2

我正在使用这个库: https ://github.com/software-mansion/react-native-gesture-handler

我对如何获取元素的实际 x,y 坐标有点困惑。我在解释...

这是初始状态:

在此处输入图像描述

在此处输入图像描述

拖动后,event.nativeEvent.absoluteX我得到了38

但我想要0因为元素得到了左侧区域。

只有当我将触摸移到最左边的区域时,我才会得到0 。像这样,

在此处输入图像描述

但在这种情况下,这种类型的解决方案对我不起作用

这是我的代码:

import React, {Component} from 'react';
import {Animated, View} from 'react-native';

import {PanGestureHandler, State} from 'react-native-gesture-handler';

export default class App extends Component {
  constructor(props) {
    super(props);
    this._translateX = new Animated.Value(0);
    this._translateY = new Animated.Value(0);
    this._lastOffset = {x: 0, y: 0};
    this._onGestureEvent = Animated.event(
      [
        {
          nativeEvent: {
            translationX: this._translateX,
            translationY: this._translateY,
          },
        },
      ],
      {useNativeDriver: true},
    );
  }

  _onHandlerStateChange = event => {
    if (event.nativeEvent.oldState === State.ACTIVE) {
      this._lastOffset.x += event.nativeEvent.translationX;
      this._lastOffset.y += event.nativeEvent.translationY;
      this._translateX.setOffset(this._lastOffset.x);
      this._translateX.setValue(0);
      this._translateY.setOffset(this._lastOffset.y);
      this._translateY.setValue(0);

      console.log(event.nativeEvent.absoluteX);
      console.log(event.nativeEvent.absoluteY);
    }
  };

  render() {
    return (
      <PanGestureHandler
        {...this.props}
        onGestureEvent={this._onGestureEvent}
        onHandlerStateChange={this._onHandlerStateChange}>
        <Animated.View
          style={{
            transform: [
              {translateX: this._translateX},
              {translateY: this._translateY},
            ],
          }}>
          <View style={{backgroundColor: 'green', height: 100, width: 100}} />
        </Animated.View>
      </PanGestureHandler>
    );
  }
}

请帮忙!提前致谢。

4

0 回答 0