【React Native】自定义拖拽Item交换及移动(带动画效果)

最近有一个业务需求需要进行拖拽item操作,稍微查了一下,没有相关的第三方组件,只能自己撸了一个,参考了一下React-Native ListView拖拽交换Item的作者思路,增加了动画效果,换一种方式实现拖拽效果,效果如下:

拖拽效果预览

主要讲一下整体的大致思路和关键代码,首先就是构造假数据以及item的样式,item的样式需要使用absolute属性来布局,以及通过top属性来控制每一个item的位置,如果不加top属性的话就会所有重叠起来;动画使用React Native自带的Animated效果实现,具体看动画,手势操作使用参考手势响应;

const DATA = [
  { name: '测试1', desc: '测试1' },
  { name: '测试2', desc: '测试2' },
  { name: '测试3', desc: '测试3' },
  { name: '测试4', desc: '测试4' },
  { name: '测试5', desc: '测试5' },
];

//定义item的top
const ITEM_TOP = 76;

constructor(props) {
    super(props);
    //保存每一个Item
    this.items = [];
    //保存每一个item的top
    this.tops = [];
    //初始化手势
    this.initHandler();
  }


//render里面方式渲染
 
  {DATA.map(this.renderItem)}
 

//每一个item
  renderItem = (item, index) => {
    
    //这里定义每一个item的top值,然后用数组保存下来
    this.tops[index] = new Animated.Value(index * ITEM_TOP);

    return (
      //使用Animated.View
       (this.items[index] = ref)}//把每个item的dom保存下来
        key={index}
        style={[
          {
            position: 'absolute',//绝对布局
            backgroundColor: 'rgba(255,255,255,0)',
            height: ITEM_HEIGHT,//自己定义的高度,随意
            width: ITEM_WIDTH,//自己定义的宽度,随意
            borderRadius: 8,
            flexDirection: 'row',
            alignItems: 'center',
          },
          { top: this.tops[index] },
        ]}
      >
     ......    
      
    );
  };

首先就是使用Animated.View组件来实现,然后定义每一个的item的top,这里用一张图解释一下


top示意图

每一个item都用一个top值来支撑,其实我们只要修改top的值,就可以进行item的拖拽操作了,这里就需要用手势进行识别,这边借用一下之前作者的说明

     onStartShouldSetPanResponder: (evt, gestureState) => true, //开启手势响应
      onMoveShouldSetPanResponder: (evt, gestureState) => true,  //开启移动手势响应
 
      onPanResponderGrant: (evt, gestureState) => {              //手指触碰屏幕那一刻触发
        
      },
      onPanResponderMove: (evt, gestureState) => {               //手指在屏幕上移动触发
        
      },
      onPanResponderTerminationRequest: (evt, gestureState) => true,   //当有其他不同手势出现,响应是否中止当前的手势
      onPanResponderRelease: (evt, gestureState) => {           //手指离开屏幕触发
        
      },
      onPanResponderTerminate: (evt, gestureState) => {         //当前手势中止触发
        
      },

我们这里主要关注的是onPanResponderGrant(按下),onPanResponderMove(移动),onPanResponderRelease(抬起)这三个。

      onPanResponderGrant: (evt, gestureState) => {
        console.log('开始点击了', locationY);
        const { pageY, locationY } = evt.nativeEvent;
        //通过屏幕的y轴获取你点击的是哪个item,要减去头部导航栏和最上方吻戏view的高度
        this.index = this._getIdByPosition(pageY - Header.HEIGHT - TITLE_HEIGHT);
        let item = this.items[this.index];
        if (item) {
          Vibration.vibrate([0, 100], false);震动一下
          item.setNativeProps({
            style: {
              zIndex: 1,修改这个item的z轴,防止移动的时候覆盖到其他view的下面
            },
          });
        }
      },

  _getIdByPosition(pageY) {
    let id = -1;
    const height = ITEM_TOP;

    if (pageY >= 0 && pageY < height * 1) {
      id = 0;
    } else if (pageY >= height * 1 && pageY < height * 2) {
      id = 1;
    } else if (pageY >= height * 2 && pageY < height * 3) {
      id = 2;
    } else if (pageY >= height * 3 && pageY < height * 4) {
      id = 3;
    } else if (pageY >= height * 4 && pageY < height * 5) {
      id = 4;
    }

    return id;
  }

这里我们通过onPanResponderGrant返回的pageY坐标来判断当前点到了哪个item,并从数组中取出这个item,通过setNativeProps()改变z轴,接下来开始拖动,并通过this.index记录下来。

      onPanResponderMove: (evt, gestureState) => {
        let top = evt.nativeEvent.pageY - Header.HEIGHT - TITLE_HEIGHT;
        let item = this.items[this.index];
        if (item) {
          //点中的item跟随手指移动
          Animated.timing(this.tops[this.index], {
            toValue: top,
            duration: 0,
          }).start();
          
          let collideIndex = this._getIdByPosition(evt.nativeEvent.pageY - Header.HEIGHT - TITLE_HEIGHT);
          if (collideIndex !== this.index && collideIndex !== -1) {
            //移动被遮住的item到上一个item的空位置
            Animated.timing(this.tops[collideIndex], {
              toValue: this.index * ITEM_TOP,
              duration: 300,
            }).start();

            //交换
            [this.items[this.index], this.items[collideIndex]] = [this.items[collideIndex], this.items[this.index]];
            [this.tops[this.index], this.tops[collideIndex]] = [this.tops[collideIndex], this.tops[this.index]];

            this.index = collideIndex;
          }
        }
      },

接下来就要先让选中的item跟随手指移动,依然通过evt获得手指移动的坐标,这个坐标就是item的终点位置,然后我们还要知道这个item原来的top值,之前我们通过tops数组进行保存,最后通过 Animated.timing()进行移动效果。

接着在通过这个手指移动的坐标,来获取collideIndex对应的item,然后取到它的top移动到手指拖拽的item的top的位置即可,最后还要进行交换维护一下item和tops的值。

      onPanResponderRelease: (evt, gestureState) => {
        let item = this.items[this.index];
        if (item) {
          item.setNativeProps({
            style: { zIndex: 0 },
          });

          Animated.timing(this.tops[this.index], {
            toValue: this.index * ITEM_TOP,
            duration: 100,
          }).start();
        }
      },

最后通过index值来还原手指拖动的z轴,以及让手指拖拽的item回到空白的位置即可。

参考

  • React-Native ListView拖拽交换Item

你可能感兴趣的:(【React Native】自定义拖拽Item交换及移动(带动画效果))