DraggableView

DraggableView.js

import React from 'react';
import {
   AppRegistry,
   View,
   Text,
   StyleSheet,
   Animated,
   PanResponder,
} from 'react-native';

// 这是一个可拖拽的自定义控件
export default class DraggableView extends React.Component{
     
     constructor(props) {
          super(props);
          this.state = {
            pan: new Animated.ValueXY(),// inits to zero
          };
          this.state.panResponder = PanResponder.create({
          	//在触摸开始的时候,这个属性接收一个回调函数,bool型,返回true,表示愿意成为响应者
            onStartShouldSetPanResponder: () => true,
            //最近一次的移动距离.如:(获取x轴y轴方向的移动距离 gestureState.dx,gestureState.dy)
            onPanResponderMove: Animated.event([null, {
              dx:this.state.pan.x,// x,y are Animated.Value
              dy:this.state.pan.y,
            }]),
            //用户放开了所有的触摸点,且此时视图已经成为了响应者 
            onPanResponderRelease: () => {
              Animated.spring(
                this.state.pan,        // Auto-multiplexed
                {toValue: {x: 0, y: 0}}// Back to zero
              ).start();
            },
          });
        }

      render() {
          return(
            <Animated.View
              {...this.state.panResponder.panHandlers}
              style={this.state.pan.getLayout()}>
              {this.props.children}
            </Animated.View>
          );
        }  

}
使用示例:

import React from 'react';
import {
   AppRegistry,
   View,
   Text,
   StyleSheet,
   Animated,
   Image,
} from 'react-native';
import DraggableView from './DraggableView';

class MyFirstProject extends React.Component{
    render() {
        return (
             <View>
                 <DraggableView>
                     <Image source={require('./img/logo.jpg')}
                            style = { {width : 200 , height: 200 }}/>
                 </DraggableView>
             </View>
        );
    }
}
AppRegistry.registerComponent('MyFirstProject', ()=> MyFirstProject);
效果图:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值