"react-native": "0.72.5",
"react-native-gesture-handler": "^2.18.0",
"react-native-reanimated": "3.3.0",(不确定是否要安装此依赖)
使用GestureDetector的方案,可能捏合会更灵敏。
import React, { ReactNode, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import {
TapGestureHandler,
PanGestureHandler,
PinchGestureHandler,
State,
} from 'react-native-gesture-handler';
interface props {
children: ReactNode,
}
const Drag = ({children}:props) => {
const [tapCount, setTapCount] = useState(0);
const [panX, setPanX] = useState(0);
const [panY, setPanY] = useState(0);
const [scale, setScale] = useState(1);
// 点击手势
const handleTap = () => {
setTapCount(prev => prev + 1);
};
// 滑动手势
const handlePan = (event: any) => {
const { translationX, translationY } = event.nativeEvent;
console.log('滑动X: %d, Y:%d', translationX, translationY);
setPanX(translationX);
setPanY(translationY);
};
// 捏合手势
const handlePinch = (event: any) => {
const { scale: currentScale } = event.nativeEvent;
console.log('缩放倍数:', currentScale);
// setScale(prev => prev * currentScale);
};
return (
<View style={styles.container}>
{/* 点击区域 */}
{/* <TapGestureHandler onHandlerStateChange={(event) => {
if (event.nativeEvent.state === State.END) handleTap();
}}>
<View style={styles.tapBox}>
<Text>点击次数: {tapCount}</Text>
</View>
</TapGestureHandler> */}
{/* 捏合缩放区域 */}
<PinchGestureHandler
onGestureEvent={handlePinch}
// minScale={0.5}
// maxScale={2}
>
{/* 滑动区域 */}
<PanGestureHandler onGestureEvent={ e => {
handlePan(e);
}}>
{/* <View style={[styles.panBox, { transform: [{ translateX: panX }, { translateY: panY }, { scale }] }]}>
<Text>滑动位置: X={panX.toFixed(2)}, Y={panY.toFixed(2)}捏合缩放: {scale.toFixed(2)}</Text>
</View> */}
{children}
</PanGestureHandler>
</PinchGestureHandler>
{/* 捏合缩放区域
<PinchGestureHandler
onGestureEvent={handlePinch}
// minScale={0.5}
// maxScale={2}
>
<View style={[styles.pinchBox, { transform: [{ scale }] }]}>
<Text style={styles.text}> 捏合缩放: {scale.toFixed(2)}x</Text>
</View>
</PinchGestureHandler> */}
</View>
);
};
const styles = StyleSheet.create({
container: {
// flex: 1,
justifyContent: 'space-around',
alignItems: 'center',
backgroundColor: '#f0f0f0',
},
tapBox: {
width: 200,
height: 100,
backgroundColor: 'lightblue',
justifyContent: 'center',
alignItems: 'center',
},
panBox: {
width: 300,
height: 400,
backgroundColor: 'lightgreen',
justifyContent: 'center',
alignItems: 'center',
},
pinchBox: {
width: 200,
height: 200,
backgroundColor: 'pink',
justifyContent: 'center',
alignItems: 'center',
},
text: {
fontSize: 18,
fontWeight: 'bold',
},
});
export default Drag;