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);效果图: