简体   繁体   中英

React-Native panResponder array with functional component

I have a slider with 6 images and I want to be able to move each one of them using panResponder.

I wrote this code (which works, but it moves all the slider, not just one image)

    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 >
  );
}

I want to be able to drag every image, not the whole slider. Is it possible? I understand we need an array of panResponders, but how to actually do it?

Many thanks

what you have to do for. everyone. image transform it into a single component, and to each of them add a panResponder, if you do it with only one, it takes the entire current component to raise the event

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM