0

我有一个包含 6 个图像的滑块,我希望能够使用 panResponder 移动每个图像。

我写了这段代码(它有效,但它移动了所有的滑块,而不仅仅是一个图像)

    const pan = useState(new Animated.ValueXY())[0];

  const panResponder = useState(
    PanResponder.create({
      onMoveShouldSetResponderCapture: () => true, //Tell iOS that we are allowing the movement
      onMoveShouldSetPanResponderCapture: () => true, // Same here, tell iOS that we allow dragging
      onMoveShouldSetPanResponder: () => true,


      onPanResponderGrant: (e, gestureState) => {
        pan.setOffset({
          y: pan.y._value
        });
      },
  onPanResponderMove: Animated.event(
    [
      null,
      { dy: pan.y }
    ],
    {
      useNativeDriver: false,
      listener: (evt, gestureState) => {

      }
    }
  ),
  onPanResponderRelease: (evt, gestureState) => {
    //pan.flattenOffset();

    console.log(gestureState);

    if (gestureState.moveY > 710) {

      Alert.alert("Added to cart.");
    }
    else {
      Animated.spring(pan, {
        toValue: 100,
        useNativeDriver: false
      },
      ).start();
    }
  }
})
)[0];


return (
<View style={styles.container}>
  <View style={{ width, height: '100%' }}>
    <ScrollView
      horizontal
      style={{ width }}
      showsHorizontalScrollIndicator={false}
    >
      {
        products.map((product) => (
          <Animated.View key={product.id}
            style={{
              transform: [{ translateY: pan.y }]
            }}
            {...panResponder.panHandlers}
          >
            <Image
              style={{ width: width / 3, height, flex: 1 }}
              resizeMode="contain"
              source={{
                uri: product.product_image,
              }}
            />
          </Animated.View>

        ))

      }

    </ScrollView>
  </View>
  <View style={styles.cart}>
    <Text style={styles.cartText}>Here comes the cart</Text>
  </View>
</View >
  );
}

我希望能够拖动每个图像,而不是整个滑块。可能吗?我知道我们需要一个 panResponder 数组,但实际上该怎么做呢?

非常感谢

4

0 回答 0