这是一个常见的问题,通常会出现在我们使用PanResponder手势操作时。它会导致视图回弹到它的原始位置,而不是平缓地过渡回去。
以下是一个示例代码,展示如何使用Animated API来解决这个问题:
import React, { useRef } from 'react';
import { Animated, PanResponder, View } from 'react-native';
const Example = () => {
const position = useRef(new Animated.ValueXY()).current;
const panResponder = useRef(
PanResponder.create({
onMoveShouldSetPanResponder: () => true,
onPanResponderGrant: () => {
position.setOffset({
x: position.x._value,
y: position.y._value,
});
position.setValue({ x: 0, y: 0 });
},
onPanResponderMove: Animated.event([
null,
{ dx: position.x, dy: position.y},
]),
onPanResponderRelease: () => {
Animated.spring(position, {
toValue: { x: 0, y: 0 },
useNativeDriver: true,
}).start();
},
})
).current;
return (
);
};
export default Example;
在这个示例中,我们使用了一个useRef
来存储Animated.ValueXY()
实例的引用。在
声明中,我们应用了变换,作为视图的位置,并将其绑定到手势处理函数中。此外,在onPanResponderRelease
事件中,我们使用了Animated.spring()
,它提供了一个平缓过渡