FlatList 中的 React Native 滑动项与 TouchableOpacity 的 onPress 冲突

问题描述

我使用 PanGestureHandler 在我的 FlatList 中创建了一个可滑动的行并重新激活了 2。 但是,当您按下该行时,我的滑动与 TouchableWithoutFeedback/TouchableOpacity 发生冲突。我尝试使用 runOnJS(onStart)() 这样做,它禁用了父组件中的 TouchableOpacity,但没有成功。我认为这是因为如果 onPress 在禁用之前注册,它仍然会在发布时触发。

const Swipeable = props => {
  const { onSwipe,children,onStart,onEnd } = props
  const translateX = useSharedValue(0)
  const scaledButtonX = useSharedValue(scale(50))
  const translateXButton = useDerivedValue(() => {
    return translateX.value + scaledButtonX.value
  })
  const offsetX = useSharedValue(0);
  const onGestureEvent = useAnimatedGestureHandler({
    onStart: (_,ctx) => {
      ctx.x = translateX.value
      runOnJS(onStart)() // this disables the onPress in the parent component
    },onActive: (event,ctx) => {
      translateX.value = ctx.x + clamp(event.translationX,-9999,-ctx.x)
    },onEnd: (event,ctx) => {
      const to = snapPoint(translateX.value,event.velocityX,snapPoints)
      translateX.value = withTiming(to,{
        easing: Easing.linear,duration: 200
      })
      ctx.x = translateX.value
      runOnJS(onEnd)() // this enables it back
    }
  })

  const style = useAnimatedStyle(() => {
    return {
      transform: [{ translateX: translateX.value }],}
  })

  const buttonStyle = useAnimatedStyle(() => {
    return {
      position: 'absolute',top: 0,bottom: 0,left: 0,right: 0,flexDirection: "row",justifyContent: "flex-end",alignItems: "center",overflow: "hidden",transform: [{ translateX: translateXButton.value }]
    }
  })

  const onDelete = () => {
    translateX.value = withSequence(withTiming(-(width + scale(50))),withTiming(0,{
      duration: 500
    },() => console.log('done2')))
    // translateX.value = withTiming(0,{},() => console.log('done'))
    onSwipe()
  }

  return (
    <View style={{ position: 'relative' }}>
      <Animated.View style={buttonStyle}>
        <TouchableOpacity style={styles.deleteButtonContainer} onPress={onDelete}>
          <View style={styles.deleteButton}>
            <Icon name='x' size={scale(20)} color={Colors.darkPurple} />
          </View>
        </TouchableOpacity>
      </Animated.View>
      <PanGestureHandler failOffsetY={[-5,5]} activeOffsetX={[-5,5]} onGestureEvent={onGestureEvent}>
        <Animated.View style={style}>
          {children}
        </Animated.View>
      </PanGestureHandler>
    </View>
  )
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)