Tiempo de lectura: < 1 minutoToday we are going to create a component that will allow us to drag other elements across the screen using React Native.
The first thing we will do is create the component that we will call DragComponent.tsx and add the logic that will allow us to drag:
<
pre class=”EnlighterJSRAW” data-enlighter-language=”generic” data-enlighter-theme=”” data-enlighter-highlight=”” data-enlighter-linenumbers=”” data-enlighter-lineoffset=”” data-enlighter-title=”” data-enlighter-group=””>import React, { useRef, ReactNode, useState } from ‘react’;import { Animated, PanResponder, StyleProp, ViewStyle } from ‘react-native’;interface DragableProps { children: ReactNode; style?: StyleProp;}const DragComponent: React.FC = ({ children, style }) => { const [offset, setOffset] = useState({ x: 0, y: 0 }); const pan = useRef(new Animated.ValueXY()).current; const panResponder = PanResponder.create({ onStartShouldSetPanResponder: () => true, onPanResponderMove: (_, gesture) => { pan.setValue({ x: gesture.dx + offset.x, y: gesture.dy + offset.y }); }, onPanResponderRelease: (_, gesture) => { setOffset({ x: gesture.dx + offset.x, y: gesture.dy + offset.y }); }, }); return ( <Animated.View {…panResponder.panHandlers} style={[{ transform: [{ translateX: pan.x }, { translateY: pan.y }] }, style]}> {children} </Animated.View>
Post Views: 0
Related