You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中拖拽FlatList时阻止Pressable触发点击事件

解决React Native轮播卡片拖拽时误触跳转的问题

实现思路

通过跟踪轮播的滚动状态,在拖拽或惯性滚动过程中禁用卡片的点击事件,仅当滚动完全停止后才允许触发跳转。

具体步骤

1. 在轮播组件中添加滚动状态管理

修改CardCarousel组件,新增状态变量标记滚动状态,并绑定轮播的滚动回调更新状态:

import * as React from "react";
import { useState } from "react";
import Carousel from "react-native-reanimated-carousel";
import Card from "components/cards/Card";

function CardCarousel(props) {
  const [isScrolling, setIsScrolling] = useState(false);

  // 拖拽开始时标记为正在滚动
  const handleScrollStart = () => {
    setIsScrolling(true);
  };

  // 滚动(含惯性滚动)结束后标记停止
  const handleScrollStop = () => {
    // 延迟时长匹配轮播的动画时长,确保滚动完全结束
    setTimeout(() => {
      setIsScrolling(false);
    }, 200);
  };

  return (
    <Carousel
      scrollAnimationDuration={200}
      width={300}
      windowSize={9}
      moveSize={5}
      style={{
        width: 2000,
        height: 300,
      }}
      data={props.articleGroup.data}
      // 绑定滚动相关回调
      onScrollBeginDrag={handleScrollStart}
      onScrollEndDrag={handleScrollStop}
      onMomentumScrollEnd={handleScrollStop}
      renderItem={(article, index) => (
        <Card
          article={article.item}
          key={index + "-main-" + props.articleGroup.category}
          isScrolling={isScrolling} // 将滚动状态传递给卡片组件
        />
      )}
    />
  );
}

export default CardCarousel;

2. 在卡片组件中根据滚动状态控制交互

修改Card组件,接收滚动状态参数,禁用滚动过程中的点击事件:

import { useState, Pressable } from "react-native";

const Card = (props) => {
  const [bookmark, setBookmark] = useState(props.article.bookmark);
  const cdnURL = wrapImgCDN(props.article.image, 400);

  const routeChange = async (event) => {
    ... code to change route
  };

  const _bookmarkToggle = () => {
    // 避免拖拽时误触书签按钮
    if (props.isScrolling) return;
    bookmarkToggle(props.article);
    setBookmark(!bookmark);
  };

  return (
    <Pressable
      onPress={routeChange}
      disabled={props.isScrolling} // 滚动时禁用整个卡片的点击
    >
      <WhiteCard
        {...props}
        _bookmarkToggle={_bookmarkToggle}
        cdnURL={cdnURL}
        bookmark={bookmark}
      />
    </Pressable>
  );
};

补充说明

  • 同时监听onScrollBeginDrag、onScrollEndDrag和onMomentumScrollEnd三个回调,覆盖手动拖拽、拖拽结束、惯性滚动结束所有滚动场景。
  • 使用setTimeout延迟恢复点击,是为了匹配轮播的动画时长,确保滚动动画完全结束后再允许交互。
  • 除了禁用Pressable,也可以在routeChange函数内直接判断props.isScrolling并返回,两种方式效果一致。

内容的提问来源于stack exchange,提问作者Steven Matthews

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 17:27:25