如何实现React Native拖放功能

3

我想要实现React Native的拖放功能,以便在拖放时交换组件。假设屏幕上有五个组件,一旦我开始拖动,它应该突出显示可放置的元素。一旦被放置,组件就应该互换位置。

1个回答

5
为了实现拖放功能,您需要使用pan响应器。首先,您需要定义在对象移动时要存储值的位置,您可以在状态上设置属性。
state = {
    pan: new Animated.ValueXY(),
};

那么你需要在componentWillMount中创建Pan响应器,例如:

this.panResponder = PanResponder.create({
    onStartShouldSetPanResponder : () => true,
    onPanResponderMove           : Animated.event([null,{ // <--- When moving
        dx : this.state.pan.x,
        dy : this.state.pan.y
    }]),
    onPanResponderRelease        : (e, gesture) => {} // <--- callback when dropped
});

最后,在render方法中,您需要将left和top设置为动画元素。
<Animated.View 
    {...this.panResponder.panHandlers}  
     style={[this.state.pan.getLayout(), styles.circle]}>  
      <Text style={styles.text}>Drag me!</Text>
</Animated.View>
this.state.pan.getLayout() 返回顶部和左侧位置,您需要这个来移动元素。
要交换元素,您需要实现onPanResponderRelease
有关更详细的步骤,请参阅此教程:https://moduscreate.com/blog/animated_drag_and_drop_with_react_native

我已经尝试过这个,但我想拖放圆形并交换它们及其值。 - RANVIR GORAI
然后你所要做的就是在放置元素时创建一个动画 ;) - Crysfel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接