我正在尝试实现多点触控滑块功能(基于React Native手势处理程序提供的示例代码)。
我发现,当我创建两个 TapOrPan
组件,它们单独工作正常,但当触碰 两者 滑块。
既然我使用的是两个独立的组件,为什么会出现这种情况?我到底缺了什么?
博览会链接调试。https:/snack.expo.ioaPLAoFWar。
import React, { Component } from 'react';
import { Animated, Dimensions, StyleSheet, Text, View } from 'react-native';
import {
PanGestureHandler,
TapGestureHandler,
ScrollView,
State,
} from 'react-native-gesture-handler';
export function TapOrPan({width, radius}) {
const tapRef = React.createRef();
const panRef = React.createRef();
const _id = parseInt(Math.random() * 100);
const _touchX = new Animated.Value(width / 2 - radius);
const _circleValue = new Animated.Value(-radius);
const _translateX = Animated.add(_touchX, _circleValue);
const _onPanGestureEvent = Animated.event(
[{nativeEvent: {x: _touchX}}],
{useNativeDriver: true}
);
const styles = StyleSheet.create({
horizontalPan: {
backgroundColor: '#777',
height: 120,
justifyContent: 'center',
marginVertical: 10,
},
circle: {
backgroundColor: '#fff',
borderRadius: radius,
height: radius * 2,
width: radius * 2,
},
wrapper: {
flex: 1,
},
});
function _onTapHandlerStateChange({ nativeEvent }) {
console.log(_id.toString() + ": " + JSON.stringify(nativeEvent));
if (nativeEvent.oldState === State.ACTIVE) {
// Once tap happened we set the position of the circle under the tapped spot
_touchX.setValue(nativeEvent.x);
}
}
return (
<TapGestureHandler
ref={tapRef}
onHandlerStateChange={_onTapHandlerStateChange}
>
<Animated.View style={styles.wrapper}>
<PanGestureHandler
ref={panRef}
activeOffsetX={[0, 0]}
onGestureEvent={_onPanGestureEvent}
>
<Animated.View style={styles.horizontalPan}>
<Animated.View
style={[
styles.circle,
{transform: [{translateX: _translateX}]},
]}
/>
</Animated.View>
</PanGestureHandler>
</Animated.View>
</TapGestureHandler>
);
}
export default function Example() {
const windowWidth = Dimensions.get('window').width;
return (
<ScrollView>
<TapOrPan width={windowWidth} radius={30} />
<TapOrPan width={windowWidth} radius={30} />
</ScrollView>
);
}
如果认为它不会像你想要的那样工作。没有两个不同的手指移动方向的两个坐标。有一个点的坐标,是由你所有手指的坐标计算出来的(在不同的平台上有所不同)。https:/github.comsoftware-mansionreact-native-gesture-handlerblobd3c8ff130e7d925dae7cec149098c5d042a00120androidlibsrcmainjavacomswmansiongesturehandlerPanGestureHandler.java#L44。