我正在尝试了解如何使用 Panresponder。我正在尝试创建一个“十字准线”,在用户点击的任何地方都会出现。我希望能够让它跟随用户的手指,但现在我什至无法让它显示在用户点击的地方。现在它的工作,但 X,Y 值是关闭的。我无法理解我做错了什么。
我将初始偏移量设置为 x:0 和 y:0 因为我不在乎前一个用户点击的位置。我已经尝试过使用 locationX/locationY 或 pageX/pageY 或gesture.x0/gesture.y0 的所有组合。
更奇怪的是,在我至少单击包含 panhandler 的框后,我可以单击框下方来启动 panhandler。如果我在第一次单击框内之前单击框外,则不会调用乞丐。
任何帮助都会很棒
主文件
import Line from '../components/Line';
const {width, height} = Dimensions.get('window');
const PanResponderComp = () => {
const pan = useState(new Animated.ValueXY())[0];
const [opacity, setOpacity] = useState(0);
const panResponder = useState(
PanResponder.create({
onStartShouldSetPanResponder: () => true,
// onMoveShouldSetPanResponder: () => true,
onPanResponderGrant: (e, gesture) => {
const {locationX, locationY} = e.nativeEvent;
console.log(locationX);
console.log(locationY);
pan.setOffset({x: 0, y: 0});
pan.setValue({
x: locationX,
y: locationY,
});
setOpacity(1);
},
// onPanResponderMove: (e, gesture) => {
// pan.x.setValue(gesture.dx);
// pan.y.setValue(gesture.dy);
// },
onPanResponderRelease: () => {
console.log('RELEASED');
// pan.flattenOffset();
setOpacity(0);
},
}),
)[0];
return (
<View style={styles.container}>
<View style={styles.chartContainer}>
<Animated.View
{...panResponder.panHandlers}
style={[
{borderWidth: 2, borderColor: 'green'},
StyleSheet.absoluteFill,
]}>
<Animated.View
style={{
transform: [{translateX: pan.x}],
opacity: opacity,
...StyleSheet.absoluteFill,
}}>
<Line y={height} x={0} />
</Animated.View>
<Animated.View
style={{
transform: [{translateY: pan.y}],
opacity: opacity,
...StyleSheet.absoluteFill,
}}>
<Line x={width} y={0} />
</Animated.View>
</Animated.View>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
},
titleText: {
fontSize: 14,
lineHeight: 24,
fontWeight: 'bold',
},
chartContainer: {
width: 400,
height: 400,
borderWidth: 1,
borderColor: 'orange',
},
});
export default PanResponderComp;
Line.js
import React from 'react';
import {View, Text, StyleSheet} from 'react-native';
import Svg, {Line} from 'react-native-svg';
export default ({x, y}) => {
// console.log(vertical);
return (
<Svg>
<Line
x1={'0'}
x2={x}
y1={'0'}
y2={y}
stroke={'black'}
strokeWidth={'2'}
strokeDasharray="6 6"
/>
</Svg>
);
};