javascript – 检测何时触摸另一个视图 – 使用PanResponder以本机方式拖动

前端之家收集整理的这篇文章主要介绍了javascript – 检测何时触摸另一个视图 – 使用PanResponder以本机方式拖动前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个纸牌游戏,用户可以在屏幕上拖动卡片.

如何检测卡是否已拖过其他View组件?我的可拖动卡片代码是这样的:

// A draggable card
// drag drop code example used: https://github.com/brentvatne/react-native-animated-demo-tinder
// panresponder docs: https://facebook.github.io/react-native/docs/panresponder.html

class Card extends React.Component {
  componentWillMount() {
  this.state = {
    pan: new Animated.ValueXY(),enter: new Animated.Value(1),}

  this._panResponder = PanResponder.create({

    onMoveShouldSetResponderCapture: () => true,onMoveShouldSetPanResponderCapture: () => true,onPanResponderGrant: (e,gestureState) => {
               Animated.spring(this.state.enter,{
        toValue: .75,}).start()

      this.state.pan.setOffset({x: this.state.pan.x._value,y: this.state.pan.y._value});
      this.state.pan.setValue({x: 0,y: 0});
    },onPanResponderMove: Animated.event([
      null,{dx: this.state.pan.x,dy: this.state.pan.y},]),onPanResponderRelease: (e,{vx,vy}) => {
      // do stuff when card released 
    }

    Animated.spring(this.state.enter,{
      toValue: 1,}).start()

    this.state.pan.flattenOffset();
    var velocity;

    if (vx >= 0) {
      velocity = clamp(vx,3,5);
    } else if (vx < 0) {
      velocity = clamp(vx * -1,5) * -1;
    }

    Animated.spring(this.state.pan,{
          toValue: {x: 0,y: toValue},friction: 4
    }).start()
    }
  })
}

解决方法

我不知道这是不是最好的方法,但我会得到目标视图的onLayout来获得x,y,width和height ……

< View onLayout = {({nativeEvent:{layout:{x,width,height}})=> {})} />

容器覆盖的坐标只是(x,x宽度)和(y,y高度)

onPanResponderGrant获取可拖动的位置:

onPanResponderGrant: (e) => {
  this.originX = e.pageX - e.locationX;
  this.originY = e.pageY - e.locationY;
}

onPanResponderMove你可以做这样的事情:

onPanResponderMove: (e,gestureState) => {
  const currentX0 = this.originX + gestureState.dx
  const currentY0 = this.originY + gestureState.dy 
}

draggable现在覆盖从currentX0到currentX0的宽度以及从currentY0到currentY0的高度……

您可以使用这些值来检查它是否与目标视图(x,y高度)重叠

原文链接:https://www.f2er.com/js/157361.html

猜你在找的JavaScript相关文章