gpt4 book ai didi

reactjs - 如何使用 React Native Gesture Handler v2 在长按后实现拖动?

转载 作者:行者123 更新时间:2023-12-05 04:37:18 24 4
gpt4 key购买 nike

docs说:

Simply set manualActivation to true on a PanGesture and use StateManager to fail the gesture if the user attempts to drag the component sooner than the duration of the long press.

但是,我不知道如何在 PanGesture 的回调中测量时间,因为如果我尝试使用 setTimeout,应用程序会崩溃,即使我能够使用 setTimeout,除了在触摸回调中,我无法获得对 GestureStateManager 的引用,所以我不确定如何将手势移动到START 状态。

除了 setTimeout 之外,是否还有其他工具可用于在似乎是 RN Reanimated worklet 中实现计时器?例如,我可以使用 performance.now() 吗?

这是我目前所拥有的:


const isPressed = useSharedValue(false);
const isDragging = useSharedValue(false);

const start = useSharedValue({
x: 0,
y: 0,
});

const offset = useSharedValue({
x: 0,
y: 0,
});

const gesture =
Gesture.Pan()
.manualActivation(true)
.onBegin((evt) => {
console.log('pan begin');
})
.onStart(() => {
console.log('pan start');
isPressed.value = true;
offset.value = {
x: 0,
y: 0,
};
})
.onTouchesDown((evt, state) => {
if (evt.numberOfTouches !== 1) {
state.fail();
}

isPressed.value = true;
start.value = {
x: evt.allTouches[0].x,
y: evt.allTouches[0].y,
};

// using setTimeout here causes a crash, and using runOnJS doesn't fix it

// runOnJS(setTimeout)(() => {
// isDragging.value = true;
// state.activate();
// }, 500);
})
.onTouchesMove((evt, state) => {
isPressed.value = true;

const offsetX = start.value.x - evt.allTouches[0].x;
const offsetY = start.value.y - evt.allTouches[0].y;

const dist = Math.sqrt(offsetX * offsetX + offsetY * offsetY);

if (dist > 10) {
state.fail();
}
})
.onUpdate((evt) => {
offset.value = {
x: evt.translationX,
y: evt.translationY,
};
})
.onFinalize(() => {
offset.value = {
x: 0,
y: 0,
};
isPressed.value = false;
isDragging.value = false;

console.log('pan finalize');
});

最佳答案

我可以通过使用组合手势概念和使用 bool 值 SharedValue 来实现结果。我组合了 LongPress 手势和 PanGesture,这样我就可以检测到 LongPress 何时开始并将 SharedValue bool 值设置为 true。所以基本上它会在按下按钮后经过一段时间后变为真。然后我在 onTouchesMove 函数中使用 SharedValue 来启用 Pan Gesture

const MyComponent = () => {

const isLongPressed = useSharedValue(false);

const longPress = Gesture.LongPress()
.minDuration(1000)
.onStart(event => {
isLongPressed.value = true;
});

const panGesture = Gesture.Pan()
.manualActivation(true)
.onTouchesMove((event, stateManager) => {
if (isLongPressed.value) {
stateManager.activate();
} else {
stateManager.fail();
}
})
.onUpdate(event => {
console.log(event.x);
})
.onTouchesUp(() => {
isLongPressed.value = false;
});

const composed = Gesture.Simultaneous(longPress, panGesture);

return (
<GestureDetector gesture={composed}>
<Animated.View style={styles.container}>
.........
</Animated.View>
</GestureDetector>
);
};

关于reactjs - 如何使用 React Native Gesture Handler v2 在长按后实现拖动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70715041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com