所以我有这个简单的动画,如果你拖动一个元素,它会(0, 0)
在动画结束时返回,
import React from "react"
import { SafeAreaView } from "react-native"
import { PanGestureHandler } from "react-native-gesture-handler"
import Animated, {
Easing,
runOnJS,
useAnimatedGestureHandler,
useAnimatedStyle,
useSharedValue,
withSpring,
withTiming
} from "react-native-reanimated"
const Comp: React.FC = () => {
const x = useSharedValue(0)
const y = useSharedValue(0)
const translateAnim = useAnimatedStyle(() => {
return {
transform: [{ translateX: x.value }, { translateY: y.value }]
}
})
const drag = useAnimatedGestureHandler({
onStart: (e, ctx: { startX: number; startY: number }) => {
ctx.startX = x.value
ctx.startY = y.value
},
onActive: (e, ctx) => {
runOnJS(move)(
ctx.startX,
ctx.startY,
e.translationX,
e.translationY
)
},
onEnd: (e, ctx) => {
runOnJS(end)()
}
})
function move(
startX: number,
startY: number,
translateX: number,
translateY: number
) {
x.value = withTiming(startX + translateX, {
duration: 0,
easing: Easing.linear
})
y.value = withTiming(startY + translateY, {
duration: 0,
easing: Easing.linear
})
}
function end() {
x.value = withSpring(0)
y.value = withSpring(0)
}
return (
<SafeAreaView>
<PanGestureHandler onGestureEvent={drag}>
<Animated.View
style={[
{ backgroundColor: "red", height: 100, width: 100 },
translateAnim
]}></Animated.View>
</PanGestureHandler>
</SafeAreaView>
)
}
export default Comp
如您所见,我拥有move
并end
使用函数在 JS 线程中runOnJs()
运行。
- 这是否意味着
withTiming
也将在 JS 线程上withTiming
运行或始终在 UI 线程上运行? - 也如您所见
x.value = withTiming(...)
。我应该把它包装在runOnUI()
函数中吗?或者更确切地说,当我们设置动画值时,它是否必须在 UI 线程上运行?