【发布时间】:2022-08-24 20:11:53
【问题描述】:
使用 reanimated2 和手势处理程序制作带有平移检测器的操纵杆。用户可以移动操纵杆的位置,它可以很好地在安卓手机上移动位置。但是无法在本机反应中获得操纵杆的位置,我将其发送到物联网设备。注意值在 useEffect 中没有得到更新。
如何在反应本机代码中获得 pos 值?.
这是代码
import React, {FC, useEffect} from \'react\';
import {StyleSheet, View} from \'react-native\';
import {Gesture, GestureDetector} from \'react-native-gesture-handler\';
import Animated, {
useAnimatedStyle,
useSharedValue,
} from \'react-native-reanimated\';
const BALL_SIZE = 60;
const JOY_SIZE = 300;
const Joystick: FC = () => {
const pos = useSharedValue({x: 0, y: 0});
const animStyle = useAnimatedStyle(() => {
return {
transform: [
{
translateX: pos.value.x,
},
{
translateY: pos.value.y,
},
],
};
}, [pos]);
const gesture = Gesture.Pan()
.onUpdate(e => {
if (Math.abs(e.translationX) > Math.abs(e.translationY)) {
let x = e.translationX;
if (x > 0 && x > JOY_SIZE / 2 - BALL_SIZE / 2) {
x = JOY_SIZE / 2 - BALL_SIZE / 2;
}
if (x < 0 && x < -(JOY_SIZE / 2 - BALL_SIZE / 2)) {
x = -(JOY_SIZE / 2 - BALL_SIZE / 2);
}
pos.value = {x, y: 0};
} else {
let y = e.translationY;
if (y > 0 && y > JOY_SIZE / 2 - BALL_SIZE / 2) {
y = JOY_SIZE / 2 - BALL_SIZE / 2;
}
if (y < 0 && y < -(JOY_SIZE / 2 - BALL_SIZE / 2)) {
y = -(JOY_SIZE / 2 - BALL_SIZE / 2);
}
pos.value = {x: 0, y};
}
})
.onEnd(() => {
pos.value = {x: 0, y: 0};
});
// it is not working
useEffect(() => {
console.log(pos.value);
}, [pos]);
return (
<View style={styles.circle}>
<View style={styles.horz_line} />
<View style={styles.vert_line} />
<GestureDetector gesture={gesture}>
<Animated.View style={[styles.ball, animStyle]} />
</GestureDetector>
</View>
);
};
const styles = StyleSheet.create({
circle: {
width: JOY_SIZE,
height: JOY_SIZE,
borderRadius: JOY_SIZE / 2,
borderWidth: 3,
borderColor: \'blue\',
margin: 5,
},
horz_line: {
borderTopWidth: 3,
borderColor: \'red\',
width: JOY_SIZE - 3,
height: JOY_SIZE,
position: \'absolute\',
top: JOY_SIZE / 2,
},
vert_line: {
borderLeftWidth: 3,
borderColor: \'red\',
width: JOY_SIZE,
height: JOY_SIZE - 3,
position: \'absolute\',
left: JOY_SIZE / 2,
},
ball: {
width: BALL_SIZE,
height: BALL_SIZE,
borderRadius: BALL_SIZE / 2,
position: \'absolute\',
left: JOY_SIZE / 2 - BALL_SIZE / 2,
top: JOY_SIZE / 2 - BALL_SIZE / 2,
backgroundColor: \'blue\',
},
});
export default Joystick;
标签: reactjs react-native react-native-reanimated react-native-gesture-handler