如何实现,React Native Drag-n-Drop

RAN*_*RAI 3 react-native

我想实现 react-native 拖放,以在 drop 上交换组件。假设我拖动屏幕上有五个组件应该突出显示可放置元素。一旦它被删除,组件应该被交换。

Cry*_*fel 5

为了实现拖放,您需要使用平移响应器。首先,您需要定义在对象移动时将值存储在哪里,您可以在状态上设置一个属性。

state = {
    pan: new Animated.ValueXY(),
};
Run Code Online (Sandbox Code Playgroud)

然后,您必须在componentWillMount例如以下位置创建平移响应器:

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
});
Run Code Online (Sandbox Code Playgroud)

最后,您需要在渲染方法中将 left 和 top 设置为动画元素。

<Animated.View 
    {...this.panResponder.panHandlers}  
     style={[this.state.pan.getLayout(), styles.circle]}>  
      <Text style={styles.text}>Drag me!</Text>
</Animated.View>
Run Code Online (Sandbox Code Playgroud)

this.state.pan.getLayout()返回顶部和左侧,你需要这个以中移动的元素。

为了交换元素,您需要实现onPanResponderRelease.

有关更详细的步骤,您可以查看本教程:https : //moduscreate.com/blog/animated_drag_and_drop_with_react_native